[C] Streams – File

In C, files are just streams. But unlike standard streams you need to open and close them on the fly.


1. FILE Structure

FILE is the structure for streams. The exact structure of it is platform-dependent. You can find it in the “stdio.h” file.

typedef struct


2. Opening a File

To open a file, you need to use the fopen() function.

  • FILE* fopen(const char* filename, const char* mode);

The “fopen()” function opens the file and returns a stream, or NULL on failure.

The mode may be (combinations of):

  • r : reading only
  • w : create a file for writing or overwrite it if it already exists
  • a :  create or append
  • r+ : open an existing file for reading and writing
  • w+ : create an new file for reading and writing
  • a+ : open for append
FILE *inFile = fopen("simpsons.txt", "r");
FILE *outFile = fopen("output.txt", "w");


3. Reading Data from a File

Once you have a FILE stream, the easiest way to read data from a file is to use “fscanf()” function.

  • int fscanf(FILE* stream, const char* format, …);
fscanf(inFile, "%i", &i);


4. Writing Data to a File

  • int fprintf(FILE* stream, const char* format, …);

Use the “fprintf()” function to write to the output stream.

fprintf(outFile, "Age = %i n", i);


5. Closing a File

Do not forget to close the stream once you have used it.

  • int fclose(FILE* stream);


6. Example

Create a text file “simpsons.txt” in the same directory with the exe file.

36, Homer Simpson 10, Bart Simpson 9, Lisa Simpson

You can read and write files very easily.

char name[100];
int i = 0;

FILE *inFile = fopen("simpsons.txt", "r");
FILE *outFile = fopen("output.txt", "w");

while(fscanf(inFile, "%i, %100[^n]", &i, name) == 2)
  fprintf(outFile, "Name = %s, Age = %i n", name, i);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s