¤ Home » Programming » C Tutorial » File Handling in C - Part 2 of 7

File Handling in C - Part 2 of 7

C provides a number of functions that helps perform basic file operations. Here is a list of some of the most commonly used functions:

fopen()create a new file or open an existing file
fclose()closes a file
fgetc()reads a character from a file
fputc()writes a character to a file
fgets()reads a line from a file
fputs()writes a line to a file
fscanf()reads a set of formatted data from a file
fprintf()writes a set of formatted data to a file
fread()reads structured data from a file
fwrite()writes structured data to a file
fseek()set the logical pointer to the desired point in the file
ftell()gives current position of the logical pointer in the file
rewind()resets the logical pointer to the beginning of the file

We have already explained the purpose of fopen and fclose functions. In this article and subsequent articles, we will deal with the other listed functions in detail.

Character I/O functions - fgetc, fputc

In the previous article we provided sample codes of two C programs - one for creating a text file by reading keyboard data character-by-character, and the second one read the created file and dumped its contents on the monitor character-by-character. In this article, we will delve deeper into the concept of character based file I/O operation to understand what goes on during the file read-write process. The relevant parts of the two C programs are replicated here for quick reference.

 #include <stdio.h> 

   FILE *fp; 
   char ch; 

   //Read characters from keyboard and write in file1.txt
   fp = fopen("file1.txt", "w");
   while((ch = getc(stdin)) != EOF) putc(ch,fp);

   //Read characters from file1.txt and write on the monitor
   fp = fopen("file1.txt", "r");
   while((ch = fgetc(fp)) != EOF) printf("%c",ch);

The above program uses the functions getc and putc to get one character from the keyboard (stdin is the address of the buffer associated with the keyboard) and write onto the file to be created (i.e. file1.txt opened in output mode). The function getc reads a character from the file pointed to by the file pointer, which is passed as a parameter to it. Any attempt to read the character beyond the last character of the file leads to end of file situation. The symbolic constant EOF defined in the header file stdio.h with the value of -1, represents the return status of an unsuccessful read attempt made by getc function. Alternatively the same program can be written using two other standard library functions fgetc and fputc.

 FILE *fp1, *fp2; 

 /* assume fp1 is associated with file opened in read and fp2 in write mode */ 
 while((ch = fgetc(fp1)) != EOF) fputc(ch,fp2); 

The file pointer provides important information regarding the manner in which input/output operations take place in a file. It is very important to keep track of the position from where the next attempt for any I/O operation can be initiated. A logical pointer does that job (the third member of the FILE structure).

We explain the steps with a file file1.txt, which contains a line of text This is a sample text file.

 fp = fopen("file1.txt","r"); 

The fopen statement will set the logical pointer to the starting byte of the file. Here the offset is 0, and the current position is 1.

The current position is the starting byte of the file from where next request of I/O operation starts. At this point the offset is 0 bytes (offset is determined by number of bytes that precede the current position). The offset position of a file can be determined using ftell function that takes the file pointer as parameter. The fgetc function shifts the logical pointer to the next character position in the text stream.

 ch = fgetc(fp);

The above statement will read one character from the file into the variable ch. Here the offset is 1, and the current position is 2.

As the program continues to read from the file, the logical pointer keeps shifting and is always positioned at the next character to be read.

Try the following program as exercise

This is a program to copy a file using the concept we have learned so far. We have already seen how to open a file and read its contents. We have also seen how to write into a file. Now, we will combine the two concepts to create a program which reads text from file1.txt and writes it to file2.txt. Essentially, the program reads a character from file1 and writes it to file2. It continues to do so character-by-character until it reaches the end of file1.

 Program to create a copy of file1.txt as file2.txt

#include <stdio.h> 

  FILE *fp1, *fp2;
  char ch; 

  fp1 = fopen("file1.txt", "r");
  if(fp1 == NULL)
	puts("Error!! Unable to open file1.txt for reading.");

  fp2 = fopen("file2.txt", "w");
  if(fp2 == NULL)
	puts("Error!! Unable to create file2.txt.");

  while((ch = fgetc(fp1)) != EOF) fputc(ch, fp2);

You can test the above program by creating a text file named file1.txt using any standard text editor such as Notepad. Make sure to put file1.txt in the same directory where your compiled exe file will be created. After running the program you will find file2.txt created in the same directory. Open file2.txt with your text editor to verify.


comments powered by Disqus

Buy Domain & Hosting from the most reliable and trusted company - WebServicesWorldWide.com.

Looking to build a website?
Launch a 20 page website in 1 day at only Rs.200/month or US$ 3.19/month. Hosting & Email included.

About the Author

Rajeev Kumar
CEO, Computer Solutions
Jamshedpur, India

Rajeev Kumar is the primary author of How2Lab. He is a B.Tech. from IIT Kanpur with several years of experience in IT education and Software development. He has taught a wide spectrum of people including fresh young talents, students of XLRI, industry professionals, and govt. officials.

Rajeev has founded Computer Solutions & WebServicesWorldwide.com, and has hands-on experience of building variety of web applications and portals, that include - SAAS based ERP & e-commerce systems, independent B2B, B2C, Matrimonial & Job portals, and many more.

Copyright © How2Lab.com. All rights reserved.

Refer a friend | Sitemap | Disclaimer | Privacy Policy