filename is the name of the file, which may include a path such as "data/marks.txt". mode says how the file will be used. fopen returns a FILE * for the opened stream, or NULL if the file cannot be opened (it does not exist, permission is denied, the folder is missing, and so on).
Mode strings
Mode
Opens for
If the file exists
If it does not exist
"r"
Reading
Read from the start
Fails (returns NULL)
"w"
Writing
Contents are erased
Created
"a"
Appending (writing at the end)
New data added at the end
Created
"r+"
Reading and writing
Kept; start at the beginning
Fails
"w+"
Reading and writing
Contents are erased
Created
"a+"
Reading and appending
Kept; all writes go to the end
Created
Adding b (for example "rb", "wb", "r+b" or "rb+") opens the file in binary mode. Adding t ("rt") is accepted by some compilers on Windows but is not part of standard C: without b, a file is already opened in text mode.
Always check the result
Pattern
fp = fopen("marks.txt", "r");if (fp == NULL) { /* report the problem and stop or recover */}
The function perror prints your message followed by the system’s reason for the last failure, which is very helpful when debugging.
fclose
Prototype
int fclose(FILE *fp);
fclose writes out any data still in the buffer, releases the buffer and closes the stream. It returns 0 on success and EOF on failure. After fclose(fp), the pointer must not be used again unless the file is reopened. Files left open are closed when the program ends normally, but closing them yourself is good practice: the number of files a program may have open at once is limited, and unclosed output may be lost if the program crashes.
Key takeaways
fopen returns a FILE *, or NULL on failure; always check.
"r" needs an existing file; "w" creates or erases; "a" creates or appends; + adds the other direction; b means binary.
fclose flushes the buffer and closes the stream; it returns 0 on success.
Use perror to see why an operation failed.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain the difference between modes "r+" and "w+".
Show worked answer
Both allow reading and writing. "r+" requires the file to exist already and keeps its contents, starting at the beginning; if the file is missing, fopen fails. "w+" creates the file if it does not exist and erases it if it does, so it always starts with an empty file. Use "r+" to update an existing file and "w+" to build a new file that you also want to read back.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/file-handling/opening-and-closing-files/ to read this page.