DATA FILE HANDLING

|TEXT FILE OPERATIONS|

The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. What this really means is that we must tell the system that we want to write to a file and what the file name is. We do this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type.

/* Program to create a file and write some data the file */

#include <stdio.h>
#include <string.h>
main( )
{
     FILE *fp;
     char stuff[25];
     int index;
     fp = fopen("TENLINES.TXT","w"); /* open for writing */

     strcpy(stuff,"This is an example line.");
     for (index = 1; index <= 10; index++)
     fprintf( fp,"%s Line number %d\n", stuff, index );

     fclose(fp); /* close the file before ending program */
}



#include <stdio.h>
   main( )
   {
     FILE *fp;
     char c;

     funny = fopen("TENLINES.TXT", "r");

     if (fp == NULL)

printf("File doesn't exist\n");
     else {

      do {
          c = getc(fp); /* get one character from the file
       
         putchar(c); /* display it on the monitor
       
           } while (c != EOF); /* repeat until EOF (end of file)
     
     }
    fclose(fp);
   }

//////// while ( !feof(fp) )

char c;

getchar(c) <- takes a character from the keyboard and puts it in variable c.
getc(c) <- takes a character from the file and puts it in variable c.

putchar(c) <- takes the value in varaible c and displays it on monitor.
putc(c) <- takes the value in variable c and puts it in file.

int a;

getw(a) <- takes integer value from file to a.
putw(a) <- puts interger value from a to file.

putc( ch, fp);
ch = getc( fp );


The EOF (END OF FILE) character from file; ( getc, getw )



The basic file operations are
  • fopen - open a file- specify how its opened (read/write) and type (binary/text)
  • fclose - close an opened file
  • fread - read from a file
  • fwrite - write to a file
  • fseek/fsetpos - move a file pointer to somewhere in a file.
  • ftell/fgetpos - tell you where the file pointer is located.

usage of fprintf( fp, "string message", variable_values )

Modes: 

 "r" - reading

Writing (w) :

#include <stdio.h>
int main()
{
 FILE *fp;
 file = fopen("file.txt","w");
 /*Create a file and add text*/
 fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
 fclose(fp); /*done!*/
 return 0;
}

Appending (a)
#include <stdio.h>
int main()
{
    FILE *fp
    file = fopen("file.txt","a");
    fprintf(fp,"%s","This is just an example :)"); /*append some text*/
    fclose(fp);
    return 0;
}