C Tutorial – File I/O (using text files)

The file I/O functions and types in the C language are straightforward and easy to understand. To make use of these functions and types you have to include the stdio library. (Like we already did in most of the tutorials).

The file I/O functions in the stdio library are:

  • fopen – opens a text file.
  • fclose – closes a text file.
  • feof – detects end-of-file marker in a file.
  • fscanf – reads formatted input from a file.
  • fprintf – prints formatted output to a file.
  • fgets – reads a string from a file.
  • fputs – prints a string to a file.
  • fgetc – reads a character from a file.
  • fputc – prints a character to a file.

File I/O: opening a text file

The fopen library function is used to open a text file. You also have to use a specified mode when you open a file. The three most common modes used are read (r), write (w), and append (a). Take a look at an example:


	#include<stdio.h>

	int main()
	{
		FILE *ptr_file;
		int x;

		ptr_file =fopen("output.txt", "w");

		if (!ptr_file)
			return 1;

		for (x=1; x<=10; x++)
			fprintf(ptr_file,"%d\n", x);

		fclose(ptr_file);

		return  0;
	}

So let’s take a look at the example:

ptr_file =fopen(“output”, “w”);

The fopen statement opens a file “output.txt” in the write (w) mode. If the file does not exist it will be created. But you must be careful! If the file exists, it will be destroyed and a new file is created instead. The fopen command returns a pointer to the file, which is stored in the variable ptr_file. If the file cannot be opened (for some reason) the variable ptr_file will contain NULL.

if (!ptr_file)

The if statement after de fopen, will check if the fopen was successful. If the fopen was not successful, the program will return a one. (Indicating that something has gone wrong).

for (x=1; x<=10; x++)

This for loop will count to ten, starting from one.

fprintf(ptr_file,”%d\n”, x);

The fprintf statement should look very familiar to you. It can be almost used in the same way as printf. The only new thing is that it uses the file pointer as its first parameter.

fclose(ptr_file);

The fclose statement will close the file. This command must be given, especially when you are writing files. So don’t forget it. You have to be careful that you don’t type “close” instead of “fclose”, because the close function exists. But the close function does not close the files correctly. (If there are a lot of files open but not closed properly, the program will eventually run out of file handles and/or memory space and crash.)

File I/O: reading a text file

If you want to read a file you have to open it for reading in the read (r) mode. Then the fgets library functions can be used to read the contents of the file. (It is also possible to make use of the library function fscanf. But you have to be sure that the file is perfectly formatted or fscanf will not handle it correctly). Let’s take a look at an example:


	#include<stdio.h>

	int main()
	{
    		FILE *ptr_file;
    		char buf[1000];

    		ptr_file =fopen("input.txt","r");
    		if (!ptr_file)
        		return 1;

    		while (fgets(buf,1000, ptr_file)!=NULL)
        		printf("%s",buf);

		fclose(ptr_file);
    		return 0;
	}

Note:The printf statement does not have the new-line (\n) in the format string. This is not necessary because the library function fgets adds the \n to the end of each line it reads.

A file “input.txt” is opened for reading using the function fopen en the mode read (r). The library function fgets will read each line (with a maximum of 1000 characters per line.) If the end-of-file (EOF) is reached the fgets function will return a NULL value. Each line will be printed on stdout (normally your screen) until the EOF is reached. The file is then closed and the program will end.

That’s all for this tutorial.

This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There are currently 31 responses to “C Tutorial – File I/O (using text files)”

Why not let us know what you think by adding your own comment!

  1. pravin on January 19th, 2011:

    hello sir/madam
    i am doing my final yr B.E. mechanical engg, u tutorial helped me much in obtaining output file in txt format, thank a lot for ur help

  2. gauti on September 19th, 2011:

    awsm πŸ™‚

  3. Lmajor on November 18th, 2011:

    I loove you. First year student at university with no programming experience looking for something like this to process some files for an assignment.

    Thank you and I loooooooooooooove you for this.

    From Barbados.

  4. siva krishna on December 1st, 2011:

    very usefull..thank you ..

  5. dhivu on April 1st, 2012:

    superb….clearly understandable….thnk u…expecting more like this…..

  6. grishma on September 4th, 2012:

    very short and sweet programs
    thanx…………

  7. steven on October 26th, 2012:

    concise and to the point, got me started with fprintf no problem, thank you , steve

  8. Abel on November 14th, 2012:

    Thanks!!! I am going through a C database book that doesn’t explain how this works. I really enjoy how you made it simple thanks. Do you have a complete tutorial online of everything C? I would love to go through it if you do

  9. reshmy on November 26th, 2012:

    thanks..its very simple explanation about files..& also expecting more like this…..

  10. ramu on December 27th, 2012:

    hello these are vry usefull for me so please send the complecated problem to my mail

  11. Yanik on January 2nd, 2013:

    Thanks in advance, it was very simple (like that)and rather helpful… Thanks again

  12. santosh on January 27th, 2013:

    hello sir/madam

    this is what i was looking for….. thanks …

  13. judyann on February 9th, 2013:

    I’m a first year college student and this is very useful for my report thank you ! πŸ˜€

  14. Mohamed on March 6th, 2013:

    What is “FILE” in :
    FILE ptr_file

    is it a variable type ?

  15. S MORU on March 14th, 2013:

    Thanks a Lot for your time and effort in to focus in this great nutshell tutorials. This is a real example in how to teach the concepts to everyone.

    Thanks a Lot…

    Sal

  16. unikl on April 26th, 2013:

    thanks for the info, this will be in my final exams!:)

  17. Ankie on May 5th, 2013:

    Thanks a lot…
    Nice tutorial…..

  18. Manzoor Mustafa on May 8th, 2013:

    Really I liked it. You approach of defining the things is best

  19. kapkwen on June 18th, 2013:

    The tutorial itself is short and precise void of spaghetti contents! Be blessed.

  20. raja on June 25th, 2013:

    thanks!!!!!!!!!!,but i have a doubt,how to check the number of letters in each line of a file

  21. sahadat sarkar on July 13th, 2013:

    this example is really helpfull 4 first time programming in c….thanks a lot!!

  22. Apurva Popat on September 16th, 2013:

    Hello Sir/Madam,

    This tutorial was really helpfull for me to learn file operation. I
    was able to create input.txt file in C:\TC\BIN folder (By default). And
    now my question is that how to create file on specific path?

    Thanking you.

  23. Salma on September 17th, 2013:

    Osome πŸ™‚ Expecting more like this..

  24. Ravikumar.R on October 5th, 2013:

    Really nice …! simple & Neat explanation of Pointers

  25. Jake.S on October 19th, 2013:

    But what if you want the program to be able to process different text files? Not just a hard coded single file like in the example. Like opening the program with a passed in text file from a command line. Like:
    cat bunchofwords.text | wordprogram.c
    and want to be able to use a different text file each time. How will the program read the file? scan?

  26. Ken on November 5th, 2013:

    Thanks alot, this site really helps me

  27. wissal on November 17th, 2013:

    it is so helpful
    thanks

  28. Arsalan on November 19th, 2013:

    Awesome . very productive .

  29. HEMANt Kuralkar on December 30th, 2013:

    Marvellous…..!!!!!!!!

  30. Arif on January 18th, 2014:

    one of the best online tutorial. Nice language. easy to understand. good for beginner. loved it.

  31. carl on February 10th, 2014:

    how do you get the code to print the numbers on the same line. Thanks