Explain input output operation on files in C with example
INPUT/OUTPUT OPERATIONS ON FILES:
Once a file is opened , reading out or writing to it is accomplish ed by using the standard I/O routines.
The getc() and putc() Functions:
The simplest file I/O function are getc() and putc(). These are analogous to getchar and putchar function and handle one character at a time. Assume that a file is opened with mode wand file pointer fp1. Then statement
Writes the character contained in character variable c to file associated with FILE
pointer fp1.
Similarly getc() is used to read a character from a file that has been opened in read
mode.
The statement
Would read a character from the file whose file pointer is fp2.
The getw() and putw() Functions:
The getw and putw are integer oriented functions. They are similar to the getc and putc
functions and are used to read and write integer values. These function would be useful
when we deal with only integer data. The general forms of getw and putw are:
The fprintf() and fscanf() Functions:
Most complier support two other functions, namely fprintf and fscanf that can handle a
group of mixed data simultaneously.
The function fprintf and fscanf performsI/O operation that are similar to printf and scanf
function, except they work on files.
The general form of fprintf is:
• Where fp is the file pointer associated with the file that has been opened for writing.
• The control string contains output specification for the items in the list
• The list may include variables, constants and strings.
For example:
fprintf(f1, “%s%d%f” ,name,age,7.5);
The general form of fprintf is:
For example:
fscanf(f2, “%s%d” ,item, &quqntity);
Like scanf , fscanf also returns the number of items that are successfully read. When the
end of file is reached, it returns the value EOF.