P14 File Handling in C

download P14 File Handling in C

of 33

Transcript of P14 File Handling in C

  • 8/3/2019 P14 File Handling in C

    1/33

    File Handling in C

  • 8/3/2019 P14 File Handling in C

    2/33

    Roadmap

    File

    File variable declaration

    File open and Close

    File read and write

    Pre-opened files

    Binary I/O

  • 8/3/2019 P14 File Handling in C

    3/33

    Files

    A file is a collection of related data. C

    treats a file as a series of bytes. Many

    files reside on disk; however, devices liketerminals, printers, and magnetic tapes

    are also considered files.

  • 8/3/2019 P14 File Handling in C

    4/33

    The C library contains a large numberofroutines for manipulating files. Thedeclarations for the structures and

    functions used by the file functions arestored in the standard include file. Before doing anything with files,you must put the line:

    #include

  • 8/3/2019 P14 File Handling in C

    5/33

    How toopen a file?

    Fir stly it searcheson the disk the file to be opened.

    Then it loads the file from the disk into a place in

    memory called buffer.

    It sets up a character pointer that points to the first

    characterof the buffer.

  • 8/3/2019 P14 File Handling in C

    6/33

  • 8/3/2019 P14 File Handling in C

    7/33

    File variable Declaration

    The declaration for a file variable is:

    FILE *file-variable; /* comment*/

    For example:

    #include

    FILE *in_file; /* file containing the input data*/

  • 8/3/2019 P14 File Handling in C

    8/33

    Fopen() and Fclose()

    Before a file can be used, it must be opened usingthe function fopen. fopen returns a pointer to the filestructure for the file. The format for fopen is:

    file-variable = fopen(name, mode);

    where:

    file-variable

    is a file variable. A value of NULL is returned on error.

    name

    is the actual name of the file (data.txt, temp.dat, etc.).

  • 8/3/2019 P14 File Handling in C

    9/33

    Mode

    indicates if the file is to be read or written.

    mode is "w" for writing and "r" for reading.The flag "b" can be added to indicate a

    binary file. Omitting the binary flag

    indicates an ASCII (text) file. Flags can be

    combined. So "wb" is used to write abinary file.

  • 8/3/2019 P14 File Handling in C

    10/33

    The fopen() function returns a file handle

    that will be used in subsequent I/O

    operations. If there is an I/O error, then

    the value NULL is returned:

  • 8/3/2019 P14 File Handling in C

    11/33

    Other modes "r" Searches file. If the file isopened successfully fopen( ) loads

    it into memory and sets up a pointer which points to the firstcharacter in it. If the file cannot be opened fopen( ) returns NULL.Operations possible reading from a file

    "w" Searches file. If the file exists, its contents are overwritten. If

    the file doesnt exist, a new file is created. Returns NULL, if unabletoopen file. Operations possible writing to the file.

    "a" Searches file. If the file isopened successfully fopen( ) loadsit into memory and sets up a pointer that points to the last characterin it. If the file doesnt exist, a new file is created. Returns NULL, ifunable toopen file. Operations possible - adding new contents atthe end of file.

    "r+" Searches file. If isopened successfully fopen( ) loads it intomemory and sets up a pointer which points to the first character init. Returns NULL, if unable toopen the file. Operations possible -reading existing contents, writing new contents, modifyingexisting contents of the file.

  • 8/3/2019 P14 File Handling in C

    12/33

    "w+" Searches file. If the file exists, its contents are

    overwritten. If the file doesnt exist a new file is created.

    Returns NULL, if unable toopen file. Operations possible -

    writing new contents, reading them back and modifying

    existing contents of the file.

    "a+" Searches file. If the file isopened successfully fopen( )

    loads it into memory and sets up a pointer which points to the

    first character in it. If the file doesnt exist, a new file is created.

    Returns NULL, if unable toopen file. Operations possible -

    reading existing contents, appending new contents to end

    of file. Cannot modify existing contents.

  • 8/3/2019 P14 File Handling in C

    13/33

    Example 1

    FILE *in_file; /* File to read */

    in_file = fopen("input.txt", "r"); /* Open the

    input file */if (in_file == NULL) { /* Test for error */

    fprintf(stderr, "Error: Unable to input file

    'input.txt'\n");exit (8);

    }

  • 8/3/2019 P14 File Handling in C

    14/33

    Closing a file

    The function fclose will close the file. The format

    of fclose is:

    status= fclose(file-variable);

    fclose(file-variable);

    The variable statusis zero if the fclose was

    successful or nonzero for an error. If you don'tcare about the status, the second form closes

    the file and discards the return value.

  • 8/3/2019 P14 File Handling in C

    15/33

    Pre-opened files

    C provides three pre -opened files.

  • 8/3/2019 P14 File Handling in C

    16/33

    Fgetc() & Fputc()

    The function fgetc reads a single character from a file. If no more data exists in the file, the function will return theconstant EOF (EOF is defined in stdio.h ).

    ch = fgetc(file);

    Note that fgetc returns an integer, not a character. Thisreturn is necessary because the EOF flag must be anoncharacter value.

    A similar function, fputc , exists for writing a singlecharacter.

    fputc(character, file);

  • 8/3/2019 P14 File Handling in C

    17/33

    Example2

    #include

    const char FILE_NAME[] = "input.txt";

    #include

    int main()

    {

    int count = 0; /* numberof charactersseen */FILE *in_file; /* input file */

    /* characteror EOF flag from input */

    int ch;

    in_file = fopen(FILE_NAME, "r");

    if (in_file == NULL) {printf("Cannot open %s\n", FILE_NAME);

    exit(8);

    }

  • 8/3/2019 P14 File Handling in C

    18/33

    while (1) {

    ch = fgetc(in_file);

    if (ch == EOF)

    break;

    ++count;

    }

    printf("Numberof characters in %s is %d\n",

    FILE_NAME, count);

    fclose(in_file);return (0);

    }

  • 8/3/2019 P14 File Handling in C

    19/33

    Fgets() and fputs()

    The functions fgets and fputs workon one line at a time. The formatof the fgets call is:

    string_ptr= fgets(string, size, file);

    fputs issimilar to fgets except that it writes a string instead ofreading it. The format of the fputs function is:

    string_ptr= fputs(string, file);

    The parameters to fputs are similar to the ones for fgets. fputsneeds no size because it gets the size of the line to write fromthe length of the string. (It keeps writing until it hits a null, '\0'.)

  • 8/3/2019 P14 File Handling in C

    20/33

    where:

    string_ptr

    is equal tostring if the read wassuccessful, or NULL ifend -of-file or an error is detected.

    string

    is a character array in which the function places thestring.

    size

    is the size of the character array. fgets reads until it getsa line (complete with ending \n) or it readssize -1characters. It then ends the string with a null (\0).

  • 8/3/2019 P14 File Handling in C

    21/33

    Problems can occur if the size specified is

    too big. C pr ovides a convenient way of

    making sure that the size parameter is just

    right through the use of the sizeof

    operator.

    The sizeofoperator returns the size of its

    argument in bytes.

  • 8/3/2019 P14 File Handling in C

    22/33

    For example:

    charstring[100];

    . . .fgets(string, sizeof(string), in_file);

  • 8/3/2019 P14 File Handling in C

    23/33

    Fprintf()

    The function fprintf converts data and writes

    it to a file. The general form of the fprintf

    function is:

    count= fprintf(file, format,parameter-1,

    parameter-2, ...);

    fprintfhas twosister functions: printf and

    sprintf. sprintf issimilar to fprintf, except

    that the first argument is a string.

  • 8/3/2019 P14 File Handling in C

    24/33

    where:

    count

    is the numberof characterssent or -1 if anerroroccurred.

    format

    describeshow the arguments are to beprinted.

    parameter-1, parameter-2, ...

    are parameters to be converted and sent.

  • 8/3/2019 P14 File Handling in C

    25/33

    example3#include

    #include

    int main()

    {

    char name[100]; /* name of the file to use */

    FILE *in_file; /* file for input */

    printf("Name? ");Scanf(%s,&name);

    in_file = fopen(name, "r");

    if (in_file == NULL) {

    fprintf(stderr, "Could not open file\n");

    exit(8);

    }

    printf("File found\n");fclose(in_file);

    return (0);

    }

  • 8/3/2019 P14 File Handling in C

    26/33

    Example4

    int main()

    {

    int i;

    FILE *fout;

    int str[257];

    for(i=0;i

  • 8/3/2019 P14 File Handling in C

    27/33

    example4

    main()

    {

    int i = 10 ;

    char ch = 'A' ;

    float a = 3.14 ;

    charstr[20] ;

    printf ( "\n%d %c %f", i, ch, a ) ;

    sprintf ( str, "%d %c %f", i, ch, a ) ;

    printf ( "\n%s", str ) ;

    }

    In this program the printf( ) printsout the valuesofi, ch anda on the screen, whereassprintf( ) stores these valuesin the character array str.

  • 8/3/2019 P14 File Handling in C

    28/33

    Fscanf()

    scanfhassimilarsister functions: fscanf and

    sscanf. The format for fscanf is:

    number= fscanf(file, format, &parameter-1,

    ...);

  • 8/3/2019 P14 File Handling in C

    29/33

    where:

    number

    is the numberof parameterssuccessfully converted. Ifthere was input but nothing could be converted, a zero

    is returned. If no data is present, EOF is returned.file

    is a file opened for reading.

    format

    describes the data to be read.parameter-1

    is the first parameter to be read.

  • 8/3/2019 P14 File Handling in C

    30/33

    Binary I/O

    Binary I/O is accomplished through two

    routines: fread and fwrite. The syntax for

    fread is:read_size = fread(data_ptr, 1, size, file);

    fwrite has a calling sequence similar tofread:

    write_size = fwrite(data_ptr, 1, size, file);

  • 8/3/2019 P14 File Handling in C

    31/33

    where:

    read_size

    is the size of the data that was read. If this value is lessthan size, then an end-of-file or error was encountered.

    data_ptris the pointer to the data to be read. This pointer mustbe cast to a character point (char *) if the data is anytype other than a character.

    size

    is the numberof bytes to be read.file

    is the input file.

  • 8/3/2019 P14 File Handling in C

    32/33

    I request Electronics and communication

    ENGINEERING students to visit my blogfor

    more

    abhishek1ek.blogspot.com

    awhengineering.blogspot.com

  • 8/3/2019 P14 File Handling in C

    33/33