Unit - 10
Unit - 10
Jigar Dalvadi
It saves time as we can easily access any part/outcome of the code whenever required.
It helps in preserving the data or information for reusability.
There is no need to worry about storage.
And without loss of data, we can easily transfer the contents of a file.
Types of Files in C
Text file
Binary file
Following are the most important file management functions available in „C,‟
function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location
FILE *fp;
fp = fopen ("file_name", "mode");
1|P ag e
PPS – 3110003 Prepared By: Prof. Jigar Dalvadi
syntax of fclose
fclose (file_pointer);
Example
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);
Writing to a File
In C, when you write to a file, newline characters „\n‟ must be explicitly added.
2|P ag e
PPS – 3110003 Prepared By: Prof. Jigar Dalvadi
fputs() function:
fprintf()Function:
3|P ag e
PPS – 3110003 Prepared By: Prof. Jigar Dalvadi
sSyntax -
4|P ag e
PPS – 3110003 Prepared By: Prof. Jigar Dalvadi
file stream - pointer to the file. As in the example file is the pointer to the file
object "myfile.txt".
offset - This is the number of bytes that need to be offset/skip from whence.
SEEK_SET - sets the pointer at the beginning of the file. SEEK_CUR - sets the pointer
at the current position of the file SEEK_END - sets the pointer at the end of the file.
5|P ag e