Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / C
Article

Simple File Reader and Writer Program in C

Rate me:
Please Sign up or sign in to vote.
1.16/5 (15 votes)
14 Nov 20073 min read 44.3K   584   10   5
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

C communicates with files using a new datatype called a file pointer. This type is defined within stdio.h, and written as 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);
} 
  • r - open a file in read-mode, set the pointer to the beginning of the file.
  • w - open a file in write-mode, set the pointer to the beginning of the file.
  • a - open a file in write-mode, set the pointer to the end of the file.
  • rb - open a binary-file in read-mode, set the pointer to the beginning of the file.
  • wb - open a binary-file in write-mode, set the pointer to the beginning of the file.
  • ab - open a binary-file in write-mode, set the pointer to the end of the file.
  • r+ - open a file in read/write-mode, if the file does not exist, it will not be created.
  • w+ - open a file in read/write-mode, set the pointer to the beginning of the file.
  • a+ - open a file in read/append mode.
  • r+b - open a binary-file in read/write-mode, if the file does not exist, it will not be created.
  • w+b - open a binary-file in read/write-mode, set the pointer to the beginning of the file.
  • a+b - open a binary-file in read/append mode.



The maximum number of files that can be opened simultaneously is defined as FOPEN_MAX.

Closing a File

Closing a file is done using the fclose() function, which is defined as int fclose(FILE *fp);.

fclose(fp); /* close the file*/


Writing to a File

Writing to files can be done in various ways:

  • putc() - like fputc()
  • fputc() - int fputc (int character, FILE * stream); - write a character to a file
  • fputs() - int fputs (const char * string , FILE * stream); - write a string to a file
  • fprintf()- int fprintf (FILE * stream , const char * format [ , argument , ...] ); - works like printf() except that it writes to a file instead of
  • STDOUT.


just like reading from files:

  • getc() - like fgetc()
  • fgetc() - int fgetc (FILE * stream); - write a character to a file
  • fgets() - char * fgets (char * string , int num , FILE * stream); - write a string to a file
  • fscanf() - int fscanf ( FILE * stream , const char * format [ , argument , ...] ); - works like scanf() except that it reads from a file instead of STDIN


Menu

The menu will provide options for you to select from. I included the menu in a function called menu() which returns selection. this function runs in a loop untill user exits it. The selection will be handles in a switch statement and corresponding function will be executed.

int menu()
{
char option[256];
int selection;

/*print the menu*/
puts("\nMining Survey Menu");
puts("\n1. Find/Display records for a given Date"); 
puts("2. Find/Display records equal or greater to given Reading value");
puts("3. Find/Display records for a given Rating. "); 
puts("4. Quit"); 
printf("\nSelect option: "); 
scanf("%s", option);

/*grab the selection*/
selection = atoi(option);

return selection;
}

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<BUFF_SIZE>;
char file_name<BUFF_SIZE>;
char line<BUFF_SIZE>;
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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
JokeSuggestion Pin
Diego Moita16-Nov-07 6:48
Diego Moita16-Nov-07 6:48 
GeneralRe: Suggestion Pin
kennethliden16-Nov-07 16:39
kennethliden16-Nov-07 16:39 
Generalhaze Pin
gclu021214-Nov-07 15:57
gclu021214-Nov-07 15:57 
GeneralRe: haze Pin
Sean Amarasinghe14-Nov-07 17:02
Sean Amarasinghe14-Nov-07 17:02 
Generalok Pin
Imtiaz A14-Nov-07 13:23
Imtiaz A14-Nov-07 13:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.