Professional Documents
Culture Documents
Introduction
A File is a collection of related data stored in an auxiliary storage device Is it possible to retain the value of Need for file sum after program
main( ) { int a = 5, b = 5, sum; sum = a + b; } How to input large amount of data to the program? termination ?
Classifications of files
Text file:
a file of characters it cannot contain integers, floating point numbers or any other data structure to store these data types, they must be converted to their character equivalent formats
Binary file
collection of data stored in the internal format of the computer. data can be an integer / float / char /array or any other structured data except file.
EOF
ASCII value 26 (ctrl z) inserted after the last character in the text file The binary file keep track of the end of file from the number of characters present in the directory entry of the file
Operations on Files
fopen( ) Creates/opens a new file for use fclose( ) Closes a file which has been opened for use. getc( ) Reads a character from the 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.
store prog.c text.out Data Structure Structure called FILE is defined in the standard I/O function definitions: <stdio.h>. Purpose What we want to do with the file?
fopen() function
creates a new file for use general format
Mode:
r open the file for reading only w open the file for writing only a open the file for appending (or adding ) data to it
fopen( ) function
File Exist r Contents are safe File does not exist Error
w
a
Examples
Important note:
we can open and use a number of files at a time ( depends on the system !) if a file fails to open it returns NULL
fclose ()
General format for closing the file
fclose( fp );
..
fclose(fp1); fclose(fp2);
Character contained in the character variable c is written to the file associated with FILE pointer fp1
c = getc( fp2 );
Points to be noted
1. The file pointer moves by one character position for every operation of getc() or putc() 2. getc() will return an end-of-file (EOF) marker when end of the file has been reached. Therefore, the reading should be terminated when EOF is encountered
Problem..
Write a program to store Welcome to BITS in a file called bits.txt. Read the same file and display it on the monitor.