MCS-201 · Unit 8

File Handling

Section 2 of 8

Block 2 · Unit 8File Handling10 min · Section 2 of 8

8.2Opening and Closing Files

Covers IGNOU MCS-201 §8.2.1, 8.2.2

Every file must be opened before use and closed after use. This section explains fopen, its mode strings, error checking, and fclose.

fopen

Prototype
FILE *fopen(const char *filename, const char *mode);

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

ModeOpens forIf the file existsIf it does not exist
"r"ReadingRead from the startFails (returns NULL)
"w"WritingContents are erasedCreated
"a"Appending (writing at the end)New data added at the endCreated
"r+"Reading and writingKept; start at the beginningFails
"w+"Reading and writingContents are erasedCreated
"a+"Reading and appendingKept; all writes go to the endCreated

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 1 · multiple choice

What does fopen return if the file cannot be opened?

Show answer

Answer: C. NULL

fopen returns a pointer, and the null pointer signals failure. EOF is returned by input functions, not by fopen.

Question 2 · multiple choice

A file log.txt already contains 50 lines. Which mode adds new lines without losing the old ones?

Show answer

Answer: B. "a"

Append mode keeps the existing contents and writes at the end. "w" and "w+" erase the file; "r" does not allow writing.

Question 3 · multiple choice

Which mode opens an existing binary file for both reading and writing without erasing it?

Show answer

Answer: D. "r+b"

r keeps the contents, + adds writing, and b selects binary mode. "wb+" would erase the file.

Question 4 · multiple choice

What does this program print if the file none.txt does not exist?

C · open_test.c
#include <stdio.h>

int main(void)
{
    FILE *fp = fopen("none.txt", "r");
    if (fp == NULL)
        printf("not found\n");
    else {
        printf("opened\n");
        fclose(fp);
    }
    return 0;
}
Show answer

Answer: A. not found

Mode "r" does not create files, so fopen returns NULL and the first branch runs.

Question 5 · multiple choice

What does fclose do besides closing the stream?

Show answer

Answer: C. Writes any data still waiting in the buffer to the file

Buffered output is flushed before the stream is closed, which is why forgetting fclose can lose the last data written.

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.

↑ ↓ move↵ openTab switch type