- For opening a file,
fopen()function is used with the required access modes.
FILE *fp;/*variable fp is pointer to type FILE*/
fp = fopen("filename", "mode");
/*opens file with name filename , assigns identifier to fp */fopen()returnNULLif its unable to open the specified file.- File pointer
fppoints to thefileresource.- contains all information about file.
- Communication link between system and program.
- An opened file is closed by passing the file pointer to
fclose().
fclose(fp);Different modes
- Reading mode (
r) :- if the file already exists then it is opened as read-only.
- sets up a pointer which points to the first character in it.
- else error occurs.
- Writing mode (
w) :- If the file already exists then its overwritten by a new file.
- else a new file with specified name is created.
- Appending mode (
a) :- If the file already exists then it is opened.
- else new file created.
- sets up a pointer that points to the last character in it.
- any new content is appended after existing content.
Additional modes
r+opens file for both reading/writing an existing file, doesn’t delete the contents of if the existing file.w+opens file for reading and writing a new file. Overwrite if the specified already exists.a+open file for reading and writing from the last character in the file.
Random access to a file
Data in a file is basically a collection of bytes.
We can directly jump to a target byte-number in a file without reading previous data using fseek()
- syntax:
fseek(file-pointer, offset, position); - position: 0 (beginning), 1 (current), 2 (end)
- offset: number of locations to move from specified position
fseek(fp, -m, 1); // move back by m bytes from current
fseek(fp, m, 0); // move to (m+1)th byte in fileftell(fp)returns current byte position in file.rewind(fp)resets position to start of file.