SlideShare une entreprise Scribd logo
1  sur  19
File Handling




January 5, 2013   Programming and   1
File handling in C

• In C we use FILE * to represent a pointer to a file.
• fopen is used to open a file. It returns the special
  value NULL to indicate that it couldn't open the file.



       FILE *fptr;
       char filename[]= "file2.dat";
       fptr= fopen (filename,"w");
       if (fptr == NULL) {
         printf (“ERROR IN FILE CREATION”);
           /* DO SOMETHING */
       }

January 5, 2013    Programming and           2
Modes for opening files

• The second argument of fopen is the mode in
  which we open the file. There are three
• "r" opens a file for reading
• "w" creates a file for writing - and writes over
  all previous contents (deletes the file so be
  careful!)
• "a" opens a file for appending - writing on the
  end of the file
• “rb” read binary file (raw bytes)
• “wb” write binary file

January 5, 2013   Programming and      3
The exit() function
• Sometimes error checking means we want an
  "emergency exit" from a program. We want it
  to stop dead.
• In main we can use "return" to stop.
• In functions we can use exit to do this.
• Exit is part of the stdlib.h library

    exit(-1);
     in a function is exactly the same as
    return -1;
     in the main routine
January 5, 2013    Programming and      4
Usage of exit( )

FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
  printf (“ERROR IN FILE CREATION”);
/* Do something */
    exit(-1);
}

January 5, 2013   Programming and    5
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");




January 5, 2013     Programming and      6
Reading Data Using fscanf( )
•We also read data from a file using fscanf( ).

FILE *fptr;
                                        input.dat
fptr= fopen (“input.dat”,“r”);
/* Check it's open */
                                          20 30
if (fptr==NULL)
  {
    printf(“Error in opening file n”);
   }
                                           x=20
fscanf(fptr,“%d%d”,&x,&y);                 y=30

January 5, 2013   Programming and             7
Reading lines from a file using fgets( )
We can read a string using fgets ( ).
 FILE *fptr;
 char line [1000];
 /* Open file and check it is open */
 while (fgets(line,1000,fptr) != NULL) {
   printf ("Read line %sn",line);
 }

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).

January 5, 2013   Programming and          8
Closing a file

• We can close a file simply using fclose( ) and
  the file pointer.

FILE *fptr;
char filename[]= "myfile.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {                           Opening
   printf ("Cannot open file to write!n");
   exit(-1);
}
fprintf (fptr,"Hello World of filing!n");      Access
fclose (fptr);
         closing
January 5, 2013      Programming and             9
Three special streams
• Three special file streams are defined in the
  <stdio.h> header
• stdin reads input from the keyboard
• stdout send output to the screen
• stderr prints errors to an error device
  (usually also the screen)
• What might this do?
  fprintf (stdout,"Hello World!n");




January 5, 2013     Programming and       10
An example program
              Give value of i
      #include <stdio.h>
              15
      main() Value of i=15
      {       No error: But an example to show error message.
       int i;

       fprintf(stdout,"Give value of i n");
       fscanf(stdin,"%d",&i);
                                             Display on
       fprintf(stdout,"Value of i=%d n",i);
                                             The screen
       fprintf(stderr,"No error: But an example to
       show error message.n");
       }


January 5, 2013   Programming and            11
Input File & Output File redirection

  • One may redirect the input and output files to
    other files (other than stdin and stdout).
  • Usage: Suppose the executable file is a.out
          $ ./a.out <in.dat >out.dat

              No error: But an example to show error message.

                Give value of i        Display
 15             Value of i=15          screen

in.dat              out.dat
  January 5, 2013    Programming and         12
Reading and Writing a character

• A character reading/writing is equivalent to
  reading/writing a byte.
      int getchar( );
      int fgetc(FILE *fp);
      int putchar(int c);
      int fputc(int c, FILE *fp);
• Example:
    char c;
    c=getchar( );
    putchar(c);
January 5, 2013   Programming and     13
Example: use of getchar() and putchar()

#include <stdio.h>
main()
{
 int c;

printf("Type text and press return to see it again n");
printf("For exiting press <CTRL D> n");
while((c=getchar( ))!=EOF) putchar(c);
}

                        End of file
  January 5, 2013    Programming and     14
Command Line Arguments

• Command line arguments may be passed by
  specifying them under main( ).

    int main(int argc, char *argv[ ]);

              Argument
               Count      Array of Strings
                          as command line
                          arguments including
                          the command itself.


January 5, 2013   Programming and        15
Example: Reading command line arguments

  #include <stdio.h>
  #include <string.h>

  int main(int argc,char *argv[])
  {
  FILE *ifp,*ofp;
  int i,c;
  char src_file[100],dst_file[100];

   if(argc!=3){
    printf("Usage: ./a.out <src_file> <dst_file> n");
    exit(0);
    }
   else{
       strcpy(src_file,argv[1]);
      strcpy(dst_file,argv[2]);
    }
January 5, 2013         Programming and                  16
Example: Contd.
if((ifp=fopen(src_file,"r"))==NULL)
{
 printf("File does not exist.n");       ./a.out s.dat d.dat
 exit(0);
 }
if((ofp=fopen(dst_file,"w"))==NULL)     argc=3
{
 printf("File not created.n");
 exit(0);                                               ./a.out
 }                                    argv               s.dat
 while((c=getc(ifp))!=EOF){
 putc(c,ofp);
                                                         d.dat
 }
 fclose(ifp);
 fclose(ofp);
}

January 5, 2013    Programming and               17
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
January 5, 2013    Programming and             18
Example: Averaging from Command Line
#include <stdio.h>
#include <stdlib.h>                   $ ./a.out 45 239 123

int main(int argc,char *argv[])
                                     Average=135.666667
{
  float sum=0;
  int i,num;

     num=argc-1;
    for(i=1;i<=num;i++)
     sum+=atof(argv[i]);
    printf("Average=%f n",sum/(float) num);
}

January 5, 2013    Programming and             19

Contenu connexe

Tendances (19)

7.0 files and c input
7.0 files and c input7.0 files and c input
7.0 files and c input
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
Shortcuts JAVA
Shortcuts JAVAShortcuts JAVA
Shortcuts JAVA
 
File in c
File in cFile in c
File in c
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
Satz1
Satz1Satz1
Satz1
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File in C language
File in C languageFile in C language
File in C language
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Programming in C
Programming in CProgramming in C
Programming in C
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Unit5
Unit5Unit5
Unit5
 
File operations in c
File operations in cFile operations in c
File operations in c
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
File handling-c
File handling-cFile handling-c
File handling-c
 
File handling in c
File handling in c File handling in c
File handling in c
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 
File Management
File ManagementFile Management
File Management
 
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
 

Similaire à L8 file (20)

WK-12-13-file f classs 12 computer science from kv.
WK-12-13-file f classs 12 computer science from kv.WK-12-13-file f classs 12 computer science from kv.
WK-12-13-file f classs 12 computer science from kv.
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
file.ppt
file.pptfile.ppt
file.ppt
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
slides3_077.ppt
slides3_077.pptslides3_077.ppt
slides3_077.ppt
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
CInputOutput.ppt
CInputOutput.pptCInputOutput.ppt
CInputOutput.ppt
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
week-12x
week-12xweek-12x
week-12x
 
File management
File managementFile management
File management
 
Files in c
Files in cFiles in c
Files in c
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
File management
File managementFile management
File management
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
 

Plus de mondalakash2012 (13)

Snns
SnnsSnns
Snns
 
Sn reaction
Sn reactionSn reaction
Sn reaction
 
Part i
Part iPart i
Part i
 
Extra problem for 1st yr
Extra problem for 1st yrExtra problem for 1st yr
Extra problem for 1st yr
 
Elimination
EliminationElimination
Elimination
 
L12 complexity
L12 complexityL12 complexity
L12 complexity
 
L11 tree
L11 treeL11 tree
L11 tree
 
L10 sorting-searching
L10 sorting-searchingL10 sorting-searching
L10 sorting-searching
 
L6 structure
L6 structureL6 structure
L6 structure
 
L4 functions
L4 functionsL4 functions
L4 functions
 
L3 control
L3 controlL3 control
L3 control
 
L2 number
L2 numberL2 number
L2 number
 
Struct examples
Struct examplesStruct examples
Struct examples
 

L8 file

  • 1. File Handling January 5, 2013 Programming and 1
  • 2. File handling in C • In C we use FILE * to represent a pointer to a file. • fopen is used to open a file. It returns the special value NULL to indicate that it couldn't open the file. FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf (“ERROR IN FILE CREATION”); /* DO SOMETHING */ } January 5, 2013 Programming and 2
  • 3. Modes for opening files • The second argument of fopen is the mode in which we open the file. There are three • "r" opens a file for reading • "w" creates a file for writing - and writes over all previous contents (deletes the file so be careful!) • "a" opens a file for appending - writing on the end of the file • “rb” read binary file (raw bytes) • “wb” write binary file January 5, 2013 Programming and 3
  • 4. The exit() function • Sometimes error checking means we want an "emergency exit" from a program. We want it to stop dead. • In main we can use "return" to stop. • In functions we can use exit to do this. • Exit is part of the stdlib.h library exit(-1); in a function is exactly the same as return -1; in the main routine January 5, 2013 Programming and 4
  • 5. Usage of exit( ) FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { printf (“ERROR IN FILE CREATION”); /* Do something */ exit(-1); } January 5, 2013 Programming and 5
  • 6. 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"); January 5, 2013 Programming and 6
  • 7. Reading Data Using fscanf( ) •We also read data from a file using fscanf( ). FILE *fptr; input.dat fptr= fopen (“input.dat”,“r”); /* Check it's open */ 20 30 if (fptr==NULL) { printf(“Error in opening file n”); } x=20 fscanf(fptr,“%d%d”,&x,&y); y=30 January 5, 2013 Programming and 7
  • 8. Reading lines from a file using fgets( ) We can read a string using fgets ( ). FILE *fptr; char line [1000]; /* Open file and check it is open */ while (fgets(line,1000,fptr) != NULL) { printf ("Read line %sn",line); } 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). January 5, 2013 Programming and 8
  • 9. Closing a file • We can close a file simply using fclose( ) and the file pointer. FILE *fptr; char filename[]= "myfile.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { Opening printf ("Cannot open file to write!n"); exit(-1); } fprintf (fptr,"Hello World of filing!n"); Access fclose (fptr); closing January 5, 2013 Programming and 9
  • 10. Three special streams • Three special file streams are defined in the <stdio.h> header • stdin reads input from the keyboard • stdout send output to the screen • stderr prints errors to an error device (usually also the screen) • What might this do? fprintf (stdout,"Hello World!n"); January 5, 2013 Programming and 10
  • 11. An example program Give value of i #include <stdio.h> 15 main() Value of i=15 { No error: But an example to show error message. int i; fprintf(stdout,"Give value of i n"); fscanf(stdin,"%d",&i); Display on fprintf(stdout,"Value of i=%d n",i); The screen fprintf(stderr,"No error: But an example to show error message.n"); } January 5, 2013 Programming and 11
  • 12. Input File & Output File redirection • One may redirect the input and output files to other files (other than stdin and stdout). • Usage: Suppose the executable file is a.out $ ./a.out <in.dat >out.dat No error: But an example to show error message. Give value of i Display 15 Value of i=15 screen in.dat out.dat January 5, 2013 Programming and 12
  • 13. Reading and Writing a character • A character reading/writing is equivalent to reading/writing a byte. int getchar( ); int fgetc(FILE *fp); int putchar(int c); int fputc(int c, FILE *fp); • Example: char c; c=getchar( ); putchar(c); January 5, 2013 Programming and 13
  • 14. Example: use of getchar() and putchar() #include <stdio.h> main() { int c; printf("Type text and press return to see it again n"); printf("For exiting press <CTRL D> n"); while((c=getchar( ))!=EOF) putchar(c); } End of file January 5, 2013 Programming and 14
  • 15. Command Line Arguments • Command line arguments may be passed by specifying them under main( ). int main(int argc, char *argv[ ]); Argument Count Array of Strings as command line arguments including the command itself. January 5, 2013 Programming and 15
  • 16. Example: Reading command line arguments #include <stdio.h> #include <string.h> int main(int argc,char *argv[]) { FILE *ifp,*ofp; int i,c; char src_file[100],dst_file[100]; if(argc!=3){ printf("Usage: ./a.out <src_file> <dst_file> n"); exit(0); } else{ strcpy(src_file,argv[1]); strcpy(dst_file,argv[2]); } January 5, 2013 Programming and 16
  • 17. Example: Contd. if((ifp=fopen(src_file,"r"))==NULL) { printf("File does not exist.n"); ./a.out s.dat d.dat exit(0); } if((ofp=fopen(dst_file,"w"))==NULL) argc=3 { printf("File not created.n"); exit(0); ./a.out } argv s.dat while((c=getc(ifp))!=EOF){ putc(c,ofp); d.dat } fclose(ifp); fclose(ofp); } January 5, 2013 Programming and 17
  • 18. 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 January 5, 2013 Programming and 18
  • 19. Example: Averaging from Command Line #include <stdio.h> #include <stdlib.h> $ ./a.out 45 239 123 int main(int argc,char *argv[]) Average=135.666667 { float sum=0; int i,num; num=argc-1; for(i=1;i<=num;i++) sum+=atof(argv[i]); printf("Average=%f n",sum/(float) num); } January 5, 2013 Programming and 19