Introduction to File Streams in C

A string is a linear sequence of elements. Only one element of the stream is accessible at any given moment. C deals with files in terms of streams of bytes. Each stream is indicated by a file descriptor, which essentially is a number that labels the file in a table of open files. However, in C we rarely work with file descriptors directly, as their implementation is specific to the operating system on which the program is running; in standard C we instead use what is known as a file pointer. A file pointer is a pointer to a C library construct that wraps the file descriptor, thereby giving us an common interface for accessing file. 

The relationship between a file and  a stream is one to one. To create a file stream, we use the fopen() function.

#include <stdio.h>

int main(void){
    
    FILE *fp;
    
    //open the file stream
    if((fp=fopen(“testfile.txt”, “w”))==NULL){
        printf(“Problem opening the file.\n”);
    } else {
        printf(“File opened successfully.\n”);
    }
    
    if(fclose(fp)!=0){
        printf(“There was a proble closing the file.\n”);
    } else {
        printf(“File closed successfully.\n”);
    }
    
    return 0;
}

We should always check to make sure that a file stream has opened successfully. If the file stream has not been opened, then the FILE pointer variable will contain NULL. The fclose() function returns a zero if it has executed successfully.

The file mode is a string that tells C how we intend to use the file. The ‘r’ mode opens the file for reading. The ‘w’ mode creates a new text file if one does not exist, and overwrites an existing file. The ‘a’ mode opens a text file for adding text to a pre-existing file.

#include <stdio.h>

int main(void){
    
    FILE *fp;
    
    /*
     * create new file with fopen using the w mode
     */
    
    if((fp=fopen("newfile.txt", "w"))==NULL){
        printf("Could not create a new file.\n");
    } else {
        printf("The file newfile.txt has been created.\n");
    }
    
    if(fclose(fp)!=0){
        printf("Problem closing the file stream.\n");
    }
    
    return 0;
    
}

There are three predefined streams in C, the standard input stream, the standard output stream, and the standard error stream. These stream are opened automatically when the main() function of a program is invoked.

#include <stdio.h>

int main(void){
    
    FILE *fp = stdout;
    
    char *str = "Hello world!";
    
    /*
     * write "Hello World!"
     * to our screen
     */
    fwrite(str, 1, 12, fp);
    
    return 0;
    
}

To learn more about C, take a look at my Kindle book http://www.amazon.com/dp/B00A4JGE0M/

 

Advertisements