The random access memory is volatile and its content is lost once the program terminates. In order to persist the data forever, we use files.
A file data stored in a storage device. A C program can talk to the file by reading content from it and writing content to it.
File pointer
The “File” is a structure that needs to be created for opening the file. A file pointer is a pointer to this structure of the file.
File pointer is needed for communication between the file and the program.
A file pointer can be created as follows:
File opening modes in C
C offers the programmers to select a mode for opening a file.
Following modes are primarily used in c File I/O
Types of Files
There are two types of files:
- Text files(.txt, .c)
- Binary files(.jpg, .dat)
Reading a file
A file can be opened for reading as follows:
Let us assume that “Harry.txt” contains an integer
We can read that integer using:
fscanf(ptr,”%d”,&num); => fscanf is file counterpart of scanf
This will read an integer from the file in the num variable.
Quick Quiz: Modify the program above to check whether the file exists or not before opening the file.
Closing the file
It is very important to close file after read or write. This is achieved using fclose as follows:
fclose(ptr);
This will tell the compiler that we are done working with this file and the associated resources could be freed.
Writing to a file
We can write to a file in a very similar manner as we read the file
fgetc() and fputc()
fgetc and fputc are used to read and write a character from/to a file.
fgetc(ptr); => Used to read a character from file
fputc(‘c’,ptr); => Used to write character 'c' to the file
EOF: End of File
fgetc returns EOF when all the characters from a file have read. So we can write a check like below to detect the end of file.
No comments:
Post a Comment