Simple File Reader and Writer Program in C






1.16/5 (13 votes)
Nov 14, 2007
3 min read

44800

595
A program for reading writing and finding records in a file.
Introduction
In C, everything from an on-disc file to a printer is a file. In this program I will explain how to navigate in a given file and find required data according to various categories.
Opening a File
FILE *fp; /* create a pointer to the file */ i = 0; /* open the file*/ if((fp = fopen(FILE_NAME, "r")) == NULL) { perror("Could not open the file."); exit(1); }
Closing a FileClosing a file is done using the fclose() function, which is defined as int fclose(FILE *fp);. fclose(fp); /* close the file*/
|
Selecting records to show
The data read from the file will be stored in a structure. ShowRecords functions will reference that structure to print out the results.
/*show records by reading*/ void show_records_by_rating(const char* rating, struct record* data) { int found = 0; int i; int data_rating = atoi(rating); struct record struct_result[FILE_SIZE]; printf("\n"); for(i = 0; i< struct_size; i++) { if(data[i].rating == data_rating) { printf("%s %s %f %d\n", data[i].site, data[i].date, data[i].reading, data[i].rating ); strcpy(struct_result[i].site, data[i].site); strcpy(struct_result[i].date, data[i].date); struct_result[i].reading = data[i].reading; struct_result[i].rating = data[i].rating; found++; } } save_results(found, struct_result); }
Saving Results
The viewed results could be saved by specifying a file name. The results will be written to the disk using sprintf function.
void save_results(int found, struct record *data) { char res; char response; char file_name ; char line ; int i; FILE *fp; (found>0) ? printf("%d records found.\n", found) : printf("No records found\n"); if(found>0) { printf("\nSave the records? [Y/N]"); scanf("%s", response); res = toupper(response[0]); if(res == 'Y') { printf("\nEnter the file name : "); scanf("%s", file_name); fp = fopen ( file_name , "a" ); for(i = 1; i< found+1; i++) { sprintf(line, "%s %s %f %d\n", data[i].site, data[i].date, data[i].reading, data[i].rating); fprintf(fp, line, file_name); } fclose (fp); } } }
Points of Interest
Reading and writing files in C is not as easy as higher level languages like Java or C# where they provide specialised methods but C compiler generates efficient code for unmanaged Win32 or UNIX environment.
History
- Created: November 15, 2007