Saturday, December 15, 2018

File Processing

File
File is a collection of notes.
Files can be opened and manipulated using the following steps:
Declaration of file :


 "w" = write (create a new file)
   "r" = read (reading a new file, there must be a file first)
   "a" = append (adds what is already in the file)
   "r +" = read + write (read the file first, then make the file)
   "w +" = write + read (make the file first, then read the file).
   "a +" = read + append.
   "rb" = read files in binary form
   "wb" = write file in binary form

To open file in C:

FILE *fopen (const char *filename, const char *mode );

To close file in C:

        int fclose (FILE *stream);

both fclose and fopen function are defined at


Input and output file in C:
int fscanf( FILE *stream, const char *format [, argument ]... ); 

fwrite( &mhs, sizeof( mhs ), 1, fp ); 

int fprintf( FILE *stream, const char *format [, argument ]...);

Example of File Processing:

#include 
#include 

int main()
{
   int num;
   FILE *fptr;
   fptr = fopen("C:\\program.txt","w");

   if(fptr == NULL)
   {
      printf("Error!");   
      exit(1);             
   }

   printf("Enter num: ");
   scanf("%d",&num);

   fprintf(fptr,"%d",num);
   fclose(fptr);

 if ((fptr = fopen("C:\\program.txt","r")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   fscanf(fptr,"%d", &num);

   printf("Value of n=%d", num);
   fclose(fptr); 
return 0; }




By :Steven
2201852132

Computer Science and Statistics

No comments:

Post a Comment