< C Tutorial

C file input/output

← Previous

Most programs need to read and write data to disk-based storage systems. Word processors need to store text files, spreadsheets need to store the contents of cells, and databases need to store records.The C language does not contain any explicit I/O statements. All I/O operations are carried out using functions from the standard c library.

fseek(), ftell(),rewind() Functions:

  • fseek() - It is used to move the reading control to different positions using fseek function.
  • ftell() - It tells the byte location of current position of cursor in file pointer.
  • rewind() - It moves the control to beginning of the file.

In C language, we use a structure pointer of file type to declare a file.

FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following are the functions.

Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point

In the above table we have discussed about various file I/O functions to perform reading and writing on file. getc() and putc() are simplest functions used to read and write individual characters to a file.

int main()
   FILE *fp;
   char ch;
   fp = fopen("one.txt", "w"); // open file for writing
   printf("Enter data");
   while( (ch = getchar()) != EOF) {
       putc(ch,fp); // write character in file
   fclose(fp); // close the file 

   fp = fopen("one.txt", "r"); // open file for reading 
   while( (ch = getc(fp)! = EOF) {
   fclose(fp); // close the file

   return 0;
← Previous