Docstoc

File Handling in C (PDF)

Document Sample
File Handling in C (PDF) Powered By Docstoc
					                                                                                                                      9/23/2011




                                                                                 Goals
                                                     •   … how       to   open a file to write to it.
                                                     •   … how       to   open a file to read from it.
             File Handling in C                      •   … how       to   open a file to append data to it.
                                                     •   … how       to   read strings from a file.
                                                     •   … how       to   write strings to a file.




               What is a File?                                                   Buffers
• A file is a collection of related data that a      • A buffer is a “special work area” that holds data as
  computers treats as a single unit.                   the computer transfers them to/from memory.
• Computers store files to secondary storage so      • Buffers help to synchronize data the physical devices
                                                       with the program.
  that the contents of files remain intact when a
  computer shuts down.                               • The physical requirements of the devices can deliver
                                                       more data for input than a program can use at any
• When a computer reads a file, it copies the file     one time. The buffer handles the overflow data until
  from the storage device to memory; when it           a program can use it.
  writes to a file, it transfers data from memory    • Moreover, the buffer also holds data until it is
  to the storage device.                               efficient to write that data to the storage device for
                                                       output.




         File Information Table                                                  Streams
                                                     • In C, we input/output data using streams. We can associate a
• A program requires several pieces of                 stream with a device (i.e. the terminal) or with a file.
  information about a file, including the name       • C supports two types of files
                                                         – Text Stream Files
  the OS uses for it, the position of the current        – Binary Stream Files
  character, etc.
• C uses a structure called FILE (defined in
  stdio.h) to store the attributes of a file.




                                                                                                                             1
                                                                                                                         9/23/2011




   Text Streams & Binary Streams                                            Files & Streams
• Text streams consist of sequential characters     •    A file is an “independent entity” with a
  divided into lines. Each line terminates with          name recorded by the operating system.
  the newline character (\n).                       •    A stream is created by a program.
• Binary streams consist of data values such as     •    To work with a file, we must associate our
  integers, floats or complex data types, “using         stream name with the file name recorded by
  their memory representation.”                          the OS.




       Steps in Processing a File                               System-Created Streams
1. Create the stream via a pointer variable using   • C automatically creates three streams that it opens and
  the FILE structure:                                 closes automatically for us in order to communicate
                                                      with the terminal:
  FILE* spData;                                         – Stdin (reads input from the keyboard)
2. Open the file, associating the stream name           – Stdout (send output to the screen)
                                                        – Stderr (prints errors to an error device)
  with the file name.                                                  (usually also the screen)
3. Read or write the data.                          • Three special file streams are defined in the stdio.h
4. Close the file.                                    header
                                                    • We cannot re-declare these streams in our programs.
                                                    • What might this do:
                                                             fprintf (stdout,"Hello World!\n");




                                                                                  Opening a File
     Standard I/O Functions in C                    • A file must be “opened” before it can be used.
                                                               FILE *fp;
                                                              :
                                                              fp = fopen (filename, mode);
                                                        –   fp is declared as a pointer to the data type FILE.
                                                        –   filename is a string - specifies the name of the file.
                                                        –   fopen returns a pointer to the file which is used in all
                                                            subsequent file operations.
                                                        –   mode is a string which specifies the purpose of opening
                                                            the file:
                                                                  “r” :: open the file for reading only
                                                                   “w” :: open the file for writing only
                                                                  “a” :: open the file for appending data to it
                                                                                spData = fopen(“MYFILE.DAT”, “w”);
                                                                                spData = fopen(“A:\\MYFILE.DAT”, “w”);
                                                                                                                         12




                                                                                                                                2
                                                                                                                     9/23/2011




                         More On fopen                                            The exit() function
                                                                        • Sometimes error checking means we want
                                                                          an "emergency exit" from a program. We
FILE *fptr;                                                               want it to stop dead.
char filename[]= "file2.dat";
fptr= fopen (filename,"w");                                             • In main we can use "return" to stop.
if (fptr == NULL) {
   fprintf (stderr, “ERROR”);                                           • In functions we can use exit to do this.
    /* DO SOMETHING */
}                                                                       • Exit is part of the stdlib.h library
                                                                           exit(-1);
                                                                             in a function is exactly the same as
                                                                           return -1;
                  from Figure 7-3 in Forouzan & Gilberg, p. 399
                                                                            in the main routine




                       File Open Modes                                       More on File Open Modes




                                Examples                                             Closing a File
          FILE *in, *out ;                                             • When we finish with a mode, we need to close
          in = fopen (“mydata.dat”, “r”) ;                               the file before ending the program or
          out = fopen (“result.dat”, “w”);                               beginning another mode with that same file.
                                                                       • To close a file, we use fclose and the
          FILE *empl ;                                                   pointer variable:
          char filename[25];                                             fclose(spData);
          scanf (“%s”, filename);
          empl = fopen (filename, “r”) ;

                                                                  17




                                                                                                                            3
                                                                                                                                                               9/23/2011




                            Closing a file                                                  Read/Write Operations on Files

• We can close a file simply using fclose and the                                  • The simplest file input-output (I/O) function are getc and
                                                                                     putc.
  file pointer. Here's a complete "hello files".
                                                                                   • getc is used to read a character from a file and return it.
 FILE *fptr;
 char filename[]= "myfile.dat";                                                          char ch; FILE *fp;
 fptr= fopen (filename,"w");                                                             …..
 if (fptr == NULL) {                                                                     ch = getc (fp) ;
    printf ("Cannot open file to write!\n");
    exit(-1);                                                                         – getc will return an end-of-file marker EOF, when the end of the file
 }                                                                                      has been reached.
 fprintf (fptr,"Hello World of filing!\n");                                        • putc is used to write a character to a file.
 fclose (fptr);
                                                                                          char ch; FILE *fp;
                                                                                          ……
                                                                                          putc (c, fp) ;

                                                                                                                                                               20




 Example :: convert a text file to all UPPERCASE                                             Additional I/O Functions
    main() {
     FILE *in, *out ;
     char c ;

        in = fopen (“infile.dat”, “r”) ;
        out = fopen (“outfile.dat”, “w”) ;

        while ((c = getc (in)) != EOF)
           putc (toupper (c), out);
        fclose (in) ;
        fclose (out) ;
                                                                                         Examples:
    }                                                                                             fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ;
                              Use the function feof                                               fprintf (out, “\nThe result is: %d”, xyz) ;
                                     if (feof (fp))
                                        printf (“\n Reached end of file”) ;
                                                                              21




                                                                                                       Side Effect & Value
               Input Data Formatting                                                                   of fscanf/scanf
• fscanf/scanf will process input characters
  until one of the following happens:
   – The function reaches the EOF indicator.
   – The function encounters an inappropriate character.
   – The function reads in a number of characters explicitly
     programmed as a maximum width field.




                                                                                                                                                                      4
                                                                                                                                              9/23/2011




            Output Side Effect & Value                                                           Writing to a file using fprintf
                                                                                        • fprintf works just like printf and sprintf except
                                                                                          that its first argument is a file pointer.
                                                                                                 FILE *fptr;
                                                                                                 fptr= fopen ("file.dat","w");
                                                                                                 /* Check it's open */
                                                                                                 fprintf (fptr,"Hello World!\n");




                                                                                        • We could also read numbers from a file using
                                                                                          fscanf – but there is a better way.




                                 Example                                                       Reading from a file using fgets
                                                                                           • fgets is a better way to read from a file
typedef struct {                              while (1) {                                  • We can read into a string using fgets
        int roll;                                if (feof (stud)) break;
        char dept_code[6];                       fscanf (stud, “%d %s %f”, &s.roll,
        float cgpa;                                          s.dept_code, &s.cgpa);            FILE *fptr;
} STUD;                                          count ++;                                     char line [1000];
main() {                                         sum += s.cgpa;                                /* Open file and check it is open */
                                                                                               while (fgets(line,1000,fptr) != NULL) {
   FILE *stud;                                }
                                                                                                 printf ("Read line %s\n",line);
   STUD s;                                    printf (“\nThe average cgpa is %f”,              }
   float sum = 0.0;                                                    sum/count);
   int count = 0;                             fclose (stud);
   stud = fopen (“stud.dat”, “r”) ;       }
                                                                                           fgets takes 3 arguments, a string, a maximum
                                                                                           number of characters to read and a file pointer.
                                                                                           It returns NULL if there is an error (such as EOF)
                                                                                  27




        Reading from a file using fgets                                                        Using fgets to read from the keyboard
   • It is quite common to want to read every line in a
     program. The best way to do this is a while loop                                     • fgets and stdin can be combined to get a
     using fgets.                                                                           safe way to get a line of input from the user
  /* define MAXLEN at start */                                                         #include <stdio.h>
  FILE *fptr;                                                                          int main()
  char tline[MAXLEN]; /* A line of text */                                             {
  fptr= fopen ("sillyfile.txt","r");                                                     const int MAXLEN=1000;
  /* check it's open */                                                                  char readline[MAXLEN];
  while (fgets (tline, MAXLEN, fptr) != NULL) {                                          fgets (readline,MAXLEN,stdin);
                                                                                         printf ("You typed %s",readline);
     printf ("%s",tline); // Print it
                                                                                         return 0;
  }                                                                                    }
  fclose (fptr);
                        fgets takes 3 arguments, a string, a maximum
                        number of characters to read and a file pointer.
                        It returns NULL if there is an error (such as EOF)




                                                                                                                                                     5
                                                           9/23/2011




    Getting numbers from strings
• Once we've got a string with a number in it
  (either from a file or from the user typing)
  we can use atoi or atof to convert it to a
  number
• The functions are part of stdlib.h
       char numberstring[]= "3.14";
       int i;
       double pi;
       pi= atof (numberstring);
       i= atoi ("12");



 Both of these functions return 0 if they have a problem




                                                                  6

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:44
posted:1/13/2012
language:English
pages:6