Advertisment

C: Files continued

author-image
CIOL Bureau
Updated On
New Update

Input output operations on files



Once a file is opened, writing to it or reading from a file can be
accomplished using these I/O functions:




getc
() — Reads a character from a file




putc
() — Writes a character to a file




fprintf
() — Writes a set of data values to a file




fscanf
() — Reads a set of data values from a file




getw
() — Reads an integer from a file




putw
() — Writes an integer to a file




fseek
() — Sets the position to a desired point in the file




ftell
() — Gives the current position in the file (in terms of bytes from

the start)




rewind
() — Sets the position to the beginning of the file

Advertisment
  1. getc()
  2. Syntax:



    FILE *fptr;


    getc(fptr);


    This function returns a character from the file to which the filepointer fptr is
    pointing to.


  3. putc()
  4. Syntax:



    FILE *fptr;


    char c;


    putc(c,fptr);


    This function writes the contents of variable ‘c’ to the file associated
    with fptr.



    getc() and putc() are analogous to getchar() and putchar()

    and handle one character at a time. The file pointer moves by one character

    position for every operation of getc or putc. When end of file is

    reached, the getc function will return an end-of-file marker EOF.

    Therefore, the reading should be terminated when EOF is encountered.

    /* Program to illustrate the use of getc() and putc() */



     main()


     {


       FILE *fp1;


       char ch;





       printf("Enter the data
    :");



       fp1=fopen("Input","w");
    /* Open the file Input in the write mode */




       while((ch=getchar())!=EOF) /* Get
    a character from the keyboard */




       {


         putc(ch,fp1); /* Write
    the character to the file Input */




       }


       fclose(fp1); /* Close the
    file Input */







       printf("\nOutput : ")


       fp1=fopen("Input","r");
    /* Reopen the file Input but in the read mode */




       while((ch=getc(fp1))!=EOF) /* Read
    a character from the file Input */




       {


         putchar(ch); /* Display
    the character on screen */




       }


       fclose(fp1); /* Close the
    file Input */




       }


       Input


       Enter the data : This is a
    program to test input and output



       Operations in files ^Z


       Output


       Output : This is a program
    to test input and output



       Operations in files


    In this program, we enter the input data via the keyboard, which is in turn
    written character by character to a file called



    Input. The end of the data input is indicated by entering an EOF character which
    is Ctrl+Z or even Ctrl+D. Then the file Input is closed. To read from the file

    Input, the file is opened again and the program then reads its content

    character by character and displays it on the screen. Reading is terminated when

    the function getc encounters the EOF mark. Here, checking for the End Of

    File condition is important as any attempt to read past the EOF might cause the

    program to terminate with an error or result in an infinite loop situation.




















  5. getw()
  6. Syntax :



    FILE *fptr;


    getw(fptr);

  7. putw()

           Syntax:



           FILE
*fptr;



           int
i;



           putw(i,fptr);



getw
and putw are integer oriented functions and are similar to the getc

and putc functions, the difference being that getw and putw

are used to read and write integer values. These functions are useful when we

deal with only integer data. The getw() returns an integer from the file

pointed to by the filepointer fptr while putw() writes the integer i to

the file.


Example: A file named Data contains a series of integer numbers. This program

reads these numbers and then writes all the odd numbers to a file called Odd and

all even numbers to a file called Even.




/* Program to illustrate the use of getw() and putw() */




 main()


 {


   FILE fptr1, fptr2;


   int x,i;





   printf("\nEnter the numbers
\n");



   fptr1=fopen("Data","w");
/* Create Data file */




   for(x=0;x!=-1;)


   {


     scanf("%d",&x);


     putw(x,fptr1);


   }


   fclose(fptr1);





   fptr1=fopen("Data","r");


   fptr2=fopen("Even","w");


   fptr3=fopen("Odd","w");


   while((i=getw(fptr1))!=EOF) /* Read
from Data file */




   {


     if(i%2==0)


   {


     putw(i,fptr2); /* Write
to file Even */




   }


   else


   {


     putw(i,fptr3); /* Write
to file Even */




   }


   fclose(fptr1);


   fclose(fptr2);


   fclose(fptr3);





   printf("\nContents of file
Even :");



   fptr1=fopen("Even","r");


   while((i=getw(fptr1))!=EOF)


     printf("%d",i);


   fclose(fptr1);





   printf("\nContents of file
Odd :");



   fptr1=fopen("Odd","r");


   while((i=getw(fptr1))!=EOF)


   printf("%d",i);


   fclose(fptr1);


   }


Contents of file Data:


1 23 45 42 89 90 22 26 40


Contents of file Even :


42 90 22 26 40


Contents of file Odd :


1 23 45 89











































Advertisment

Continued...

Managing files



Now let’s move on to managing files in C. A file is another structured
datatype similar to an array. The characteristics of files are:

  1. File contents are stored in a permanent storage medium like disk.
  2. File data can be of different datatypes.
  3. Files can be arbitrary and of unlimited size whereas the size of an array

    is limited and has to be declared earlier.

So far, we’ve been using the scanf and printf functions to read and write

data. These are console oriented I/O functions and work fine as long as the data

is small. However, in cases that involve large volumes of data console oriented

I/O operations pose two problems:

Advertisment
  1. It becomes cumbersome and time consuming to handle large volumes of data

    through terminals.
  2. The entire data is lost when either the program is terminated or the

    computer is turned off.

Hence, it becomes necessary to have a more flexible approach where data can be

stored on the disk and read whenever necessary without destroying the data.

Hence the use of files to store data. A file is a place on the disk where a

group of related data is stored. In C, the

different I/O devices like keyboard and monitor are treated as files. The

keyboard acts as an input file and the monitor as an output file. C supports

several functions that have the ability to perform basic file operations like

opening, closing, reading, writing and naming a file.

Defining and opening a file



If we want to store data in a file in the secondary memory, we must specify
certain things about the file to the operating system. They include:

Advertisment
  1. Filename
  2. Data structure
  3. Purpose

Filename: can be made of two parts, a primary name and an optional

period with the extension. For example: trial.data, prog.c etc.



Data structure: of a file is defined as FILE in the library of
standard I/O function definitions. Therefore, all files should be declared as

type FILE before they are used. FILE is a defined datatype.



Purpose: when a file is opened we must specify the purpose i.e. what we
want to do with the file, for example whether we want to read data from the file

or write data to the file.



This is the format for declaring and opening a file:



FILE
*fp;



fp=fopen("filename","mode");


The first statement declares that variable fp is a pointer to the datatype FILE

and the second statement opens the file named filename and assigns an

identifier to the FILE type pointer fp. This pointer contains all

information about the file and is subsequently used as a communication link

between the system and the program. The ‘mode’ in the second statement

specifies the purpose of opening the file and can be one of the following:




r
    -   Open the file in the read mode only but

the file must already exist;




w
  -   Open the file in the write mode only, if the file

already exists the contents are overwritten. If it



       doesn’t
exist then a new file is opened for writing;




a
   -  Open the file in the append mode i.e. for adding data

at the end of file. If the file doesn’t exist



       a file
is created for writing. In this mode existing data is not overwritten.




r+ 
- Opens an existing file for reading and writing (the file must

exist).




w+
- Opens an empty file for reading and writing. If the file exists the

contents will be destroyed.




a+
  - The write operation results in appending of the data and existing

data will not be overwritten.

Note: both filename and mode are specified as strings and should be enclosed

in double quotation marks.



Consider the following statements:


 FILE *p1, *p2;


 p1=fopen("emp","r");


 p2=fopen("results","w");





Here, the file emp is opened for reading and results is opened for writing. If
the emp file doesn’t exist, an error will occur. In case the file results

already exists, it’s contents are deleted and the file is opened as a new

file.






Continued...Closing a file


A file must be closed as soon as all operations on it have been completed.
This ensures that all outstanding information associated with the file is

flushed out from the buffers and all links to the file are broken. It also

prevents accidental misuse of the file. In case there is a limitation on the

number of files that can be kept open simultaneously, closing any unwanted files

might help open the required files. Another instance where we would have to

close a file is when we want to reopen the same file in a different mode. Other

than these reasons, it's considered good programming practice to close

unwanted files. This is how we close a file:



 fclose(filepointer);








This closes the file associated with the FILE pointer ‘filepointer’.



Example:


 FILE *p1, *p2;


 p1=fopen("Input","w");


 p2=fopen("Output","r");


 ………………


 ………………


 fclose(p1);


 fclose(p2);


This program opens two files and closes them after all operations on them are
completed. Once a file is closed, its file pointer can be reused with another

file. All files are automatically closed whenever that program is terminated.








tech-news