Opening and Closing of File Streams in C

This C Tutorial Explains Opening and Closing of Streams using C programming.

Recall that standard I/O library makes it very convenient to reading from and/or writing to files in a C program. This requires setting up a stream with the specified file.

fopen() function is used to open a given file and associates a stream with the file. Syntax of fopen() is as follows,

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

Notice that fopen() takes two arguments as strings, first is the name of file or device you wish to open. Rules for constructing file name might differ on different systems, fopen takes only one string and not separate arguments for path, drive letter or file extension etc. Second argument is mode which indicates how you wish to open the stream whether for reading or writing or both and whether for text stream or binary stream. Most frequently used modes I’ve listed below as

Text streams “r” for reading “w” for writing “a” for appending
Binary Streams “rb” for reading “wb” for writing “ab” for appending

advertisement
advertisement

If you add “+” to a mode, this opens the stream in update mode which allows you to read from and write to the file as well. This requires you to call functions like fseek(), fsetpos(), rewind() when you wish to write to the file immediately after reading from the file. Similarly, you need to follow call to fflush() after you have written to the file but before performing reading from it. fflush() flushes the stream i.e. physically writes any data stored in the stream to the file before reading begins from it.

Further notice that if stream is opened in read mode, file from which to perform read must already exists. If stream is opened in write mode, file if already exists will be deleted and new file is created. If stream is opened in append mode, file if already exists won’t be deleted and if that’s not existing, it will be created anew. In either case, writing will be done at the end of file.

Notice that fopen() returns a pointer of type FILE structure which program saves in a pointer of FILE structure. This pointer is the stream fopen() has associated with the specified file. Because this pointer is used to access the stream associated with given file, therefore to read from or write to the file, call appropriate function and pass this pointer to it. fopen() returns NULL if it fails to open the given file. Therefore, it’s important to check if fopen() function succeeded or failed. For ex.

Note: Join free Sanfoundry classes at Telegram or Youtube
    FILE *fp;
 
    fp = fopen("hello.txt", "r");
 
    if (fp == NULL) {
        perror("file open");
        exit(EXIT_FAILURE);
    }
 
    /* here process the file */

After the stream has been opened successfully, perform the required operations and after you are done, close the stream by calling fclose() function. Syntax of which is as follows,

    int fclose(FILE *);

Notice that fclose() returns zero ‘0’ if successful EOF otherwise. It’s a good programming habit to test for operations which have probability of failure in order to sure whether or not the operation succeeded. For example,

advertisement
    if (fclose(fp) != 0) {
        perror("fclose");
        exit(EXIT_FAILURE);
    }
/* 
 * fopen_fclose.c -- program attempts to open, process and close
 * files one by one
 */
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char *argv[])
{
    int exit_status = EXIT_SUCCESS;
    FILE *fp;
    int ch;
 
    printf("**Program reads in filenames as command-line arguments,\n"
           "attempts to open stream associated with each file in read "
           "mode then\nreads from each file one-by-one, before closing "
           "each.**\n");
 
    while (*++argv != NULL) {
        /* open files */
        fp = fopen(*argv, "r");
        /* test if fopen succedded */
        if (fp == NULL) {
            /* give user error massage */
            printf("No such %s file", *argv);
            /* not to exit, instead process another file name if */
            /* there's any */
            exit_status = EXIT_FAILURE;
            continue;
        }
 
        /* here we process file */
        /* read the contents of the file line by line */
        while ((ch = fgetc(fp)) != EOF) {
            putchar(ch);
     }
 
        putchar('\n');
 
        /* Now we close the stream by passing fp to fclose() */
        /* also test if fclose did not fail */
        if (fclose(fp) != 0) {
            perror("fclose(): *argv");
            exit(EXIT_FAILURE);
        }
    }
}

Above program takes file names as command-line arguments, attempts to open stream in read mode associated with a given file and reads from it before closing it. If a file given isn’t existing, program skips that dile, sets integer exit_status to EXIT_FAILURE before attempts to open next if ther’s any otherwise stops execution.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.