Wednesday, October 13, 2010

File Handling in C Language

,

File handling means one can perform operations like create, modify, delete etc on system files. You want to read from or write to one of the files you're working with, you identify that file by using its file pointer.

File Handling Funtions :

fopen() : The fopen() function is used to open a file and associates an I/O stream with it.

The mode string "r" indicates reading. Mode "w" indicates writing, so we
could open. The third major mode is "a" for append. mode is "+" for read and write. Mode "b" character to indicate that you want to do “binary''

fread() and fwrite() : The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen function.

fseek() : The fseek() function is used to set the file position indicator for the stream to a new position.

fclose() : The fclose() function first flushes the stream opened by fopen() and then closes the underlying descriptor.

You declare a variable to store a file pointer like this:

FILE *fp;

If you were reading from one file and writing to another you might declare an input file pointer and an output file pointer:

FILE *ifp, *ofp;

One thing to beware of when opening files is that it's an operation which may fail, file might not exist, or it might be protected against reading or writing. Fopen returns a null pointer if it can't open the requested file, and it's important to check for this case before going off and using fopen's return value as a file pointer. eg:

ifp = fopen("input.dat", "r");
if(ifp == NULL)
{
 printf("can't open file\n");
 exit or return
}


Example : Writing a data to the file

#include <stdio.h>
main( )
{
  FILE *fp;
  char stuff[25];
  int index;
  fp = fopen("TENLINES.TXT","w");
  strcpy(stuff,"This is an example line.");
  for (index = 1; index <= 10; index++)
  fprintf(fp,"%s Line number %d\n", stuff, index);
  fclose(fp);
}

0 comments to “File Handling in C Language”

Post a Comment