Page 133 - DCAP408_WEB_PROGRAMMING
P. 133

Unit 8: File I/O




              exit(1);                                                                          Notes
          }
          The stream may be access via fprintf or fscanf, and should be subsequently closed with fclose. (In
          windows programs, HaltCL should be used instead of exit.)
          fclose
          fclose closes a stream previously opened with fopen. (Declared in stdio.h.)

                 int  fclose(FILE  *stream);
          A simple use of fclose might look like
                 FILE  *my_file;
          /*  ..  */
          my_file  =  fopen(“datafile.txt”,  “r”);
          /*  ..  */
          fclose(my_file);
          fprintf
          fprintf  is  the  analogue  of  printf  for  use  with  arbitrary  streams.  (Declared
          in  stdio.h.)
                 int  fprintf(FILE  *stream,  const  char  *format,  ...  );


                 Example: To open a disk-file and write some text to it:
                 FILE  *my_file;
          int  i;
          /*  ..  */
          my_file=fopen(“datafile.txt”,”w”);
          fprintf(my_file,  “i=%d”,  i);
          /*  ..  */
          fclose(my_file);
          The meaning of the second and subsequent arguments to fprintf are described in printf.
          fscanf
          fscanf  is  the  analogue  of  scanf  for  use  with  arbitrary  streams.  (Declared
          in  stdio.h.)
                 int  fscanf(FILE  *stream,  const  char  *format,  ...  );


                 Example: To open a disk-file and read some text from it:
                 FILE  *my_file;
          int  i;
          /*  ..  */
          my_file=fopen(“datafile.txt”,”r”);
          fscanf(my_file,  “%d”,  &i);    /*    read  an  integer  from  the  file  into  i    */
          /*  ..  */
          fclose(my_file);





                                           LOVELY PROFESSIONAL UNIVERSITY                                   127
   128   129   130   131   132   133   134   135   136   137   138