File I/O in C programming with examples

by Chaitanya Singh

in c-programming

Following are the operations that can be performed on a file –

a) Creating a new file
b) Writing into a file
c) Opening an existing file
d) Reading a file
e) Closing a file

Consider a small C program first –

int main()
{
     /* Pointer to the file */
     FILE *fp1;
     /* Character variable to read the content of file */
     char c;

     /* Opening a file in r mode*/
     fp1= fopen ("MYFILE.C", "r");

     /* Infinite loop –I have used break to come out of the loop*/
     while(1)
     {
        c = fgetc(fp1);
        if(c==EOF)
            break;
        else
            printf("%c", c);
     }
     fclose(fp1);
     return 0;
}

The above program is opening a file MYFILE.C in r mode, reading the content of the file and displaying it on the console. lets understand the each operation in detail -

Opening a file

fopen() function is used to open a file.
Syntax:

FILE pointer_name = fopen ("file_name", "Mode");

here pointer_name can be anything of your choice.
file_name is the name of the file, which you want to open.

While opening a file, you need to specify the mode, detailed information on this are following –
for example:

FILE  *fp;
fp = fopen("MYABC.C", "r");

Above code will open a file MYABC.C in r mode (read only mode). The address of the first character is stored in pointer fp.

How to track whether file has opened successfully?
As I discussed above, If file is not being open then the pointer will be having NULL so the below code would help you to track the status –

..
FILE fpr;
fpr = fopen("FILENAME.C", "r");
if (fpr == NULL)
{
    puts("Error while opening file");
    exit();
}

File Opening Modes:

The file is opened using fopen() function, while opening you can use any of the below mode as per the need of the program-
Mode “r”: It is a read only mode, which means if the file is opened in r mode, it won’t allow you to write and modify content of it. When fopen() opens a file successfully then it returns a pointer to the location, where the file has been loaded otherwise returns NULL.
Pointer location: On successful opening of file, the fopen() function returns a pointer, which points to the first character of the file.

Mode “w”: It is a write only mode. fopen() creates a new file when the specified file doesn’t exist and if it fails to open file then it returns NULL.

Mode “a”: Using this mode Content can be appended at the end of an existing file. Like Mode “w”, fopen() creates a new file if it file doesn’t exist. On unsuccessful open it returns NULL.
Pointer location: At the last character of the file.

Mode “r+”: This mode is same as mode “r”; however you can perform various operations on the file opened in this mode. You are allowed to read, write and modify the content of file opened in “r+” mode.
Pointer location: First character of the file.

Mode “w+”: Same as mode “w” apart from operations, which can be performed; the file can be read, write and modified in this mode.
Mode “a+”: Same as mode “a”; you can read and append the data in the file, however content modification is not allowed in this mode.
Reading a File

In order to read, the file must be opened. fopen() returns the address of the file’s element based on the mode, in which it has been open.

In our example, we have opened a file MYFILE.C in r mode. Pointer fp1 is having the address of the first element of the file. We have used a function fgetc() to read the file.

fgetc ( ): This function reads the character from current pointer’s position and upon successful reading moves the pointer to next character in the file. Upon reaching to the end of the file this function returns EOF (End of File). We have used EOF in our program to determine the end of the file. This is almost similar to getc() function.

In general, below code is sufficient for reading a file in r mode –

..
char ch;
while(1)
{
     /* reading the current character in variable ch and
      * moving the pointer forward to point next character*/
     ch = fgetc(fp);

     /*fgetc wil return EOF when it reaches to the end so
      * I’m using it to find out the end of the file, since my loop is
      * infinite, I need to use break statement to come out of it*/
     if (ch ==EOF)
         break;
     else
     /*here I can use any logic, I may write the content in another file
      *or I can display it on console*/
     printf("%c", ch);
 }
..

Writing into a file

Let’s see the code first –

/* I need to write a character into my file so first
 * I have stored it into a char variable
 */
char ch = 'a';

/* Syntax is same here, except the mode, I need to write
 * the file so I’m using “w” mode 
 */
FILE fpw = fopen("MYFILE2.C", "w");

/* fputc is writing ch variable into the address located by fpw
 * it also moves the pointer one char forward after each write
 */
fputc(ch, fpw);

Most of the things I have covered in the comments itself. Few things you must note are: mode “w” for writing, fputc syntax, this function almost similar to putch( ).

Closing a file

Code –

fclose(fp);

fclose( ) function is used for closing an opened file. As an argument you must provide a pointer of FILE type, which is currently pointing to a file.

Now you have understood all the three main operations on the file, Let’s use all three in one C program – I’ll copy content of FILE1.C to FILE2.C

#include <stdio.h>
int main()
{
    char ch;

    /* Pointer for both the file*/
    FILE *fpr, *fpw;
    /* Opening file FILE1.C in “r” mode for reading */
    fpr = fopen("FILE1.C", "r");

    /* Ensure FILE1.C opened successfully*/
    if (fpr == NULL)
    {
         puts("Input file is having issues while opening");
    }

    /* Opening file FILE2.C in “w” mode for writing*/
    fpw= fopen("FILE2.C", "w");

    /* Ensure FILE2.C opened successfully*/
    if (fpw == NULL)
    {
       puts("Output file is having issues while opening");
    }

    /*Read & Write Logic*/
    while(1)
    {
        ch = fgetc(fpr);
        if (ch==EOF)
            break;
        else
            fputc(ch, fpw);
    }

    /* Closing both the files */
    fclose(fpr);
    fclose(fpw);

    return 0;
}

How to read/ write (I/O) Strings in Files – fgets & fputs

Above we have seen how to read and write characters from/into files. Here we will learn strings I/O from/into files. We have two functions to do that –

char *fgets(char *s, int rec_len, FILE *fpr)

Consider the example first –

#include <stdio.h>
int main()
{
    FILE *fpr;
    /*Char array to store strings */
    char str[100];
    /*Opening the file in "r" mode*/
    fpr = fopen("FILER.TXT", "r");

    /*Error handling for file open*/
    if (fpr == NULL)
    {
       puts("Issue in opening the input file");
    }

    /*Loop for reading the file till end*/
    while(1)
    {
       if(fgets(str, 10, fpr) ==NULL)
            break;
       else
            printf("%s", str);
    }
    /*Closing the input file after reading*/
    fclose(fpr);
    return 0;
}

I have explained most of the operations in the example itself. The main thing I wanna discuss now – Do you see fgets function in above example? Let’s talk about it in detail –

It takes three arguments –

fgets(str, 10, fpr)

here str represents the string (array of char) in which you are storing the string after reading it from file.
10 is the length of the string need to be read every time.

fpr is pointer to file, which is going to be read.

In general –

char *fgets(char *s, int rec_len, FILE *fpr)

s – Array of characters to store strings.
rec_len – Length of the input record.
fpr – Pointer to the input file.

Why I used if(fgets(str, 10, fpr)==NULL as a logic to determine end of the file?
In previous tutorial we have used ch==EOF to get to know the end of the file. Here we have used this logic because fgets returns NULL when there is no more records are available to be read.

int fputs ( const char * s, FILE * fpw );

Sample program –

#include <stdio.h>
int main()
{
     FILE *fpw;

     /*Char array to store strings */
     char str[100];

     /*Opening the file FILEW.TXT in “w” mode for writing*/
     fpr = fopen("FILEW.TXT", "w");

     /*Error handling for output file*/
     if (fpw== NULL)
     {
          puts("Issue in opening the Output file");
     }

     printf("Enter your string:");

     /*Stored the input string into array – str*/
     gets(str);

     /* Copied the content of str into file – 
      * FILEW.TXT using pointer – fpw*/
     fputs(str, fpw);

     /*Closing the Output file after successful writing*/
     fclose(fpw);
     return 0;
}

fputs takes two arguments –

fputs(str, fpw)

str – str represents the array, in which string is stored.
fpw – FILE pointer to the output file, in which record needs to be written.

In general –

int fputs ( const char * s, FILE * fpw );

char *s – Array of char.
FILE *fpw – Pointer (of FILE type) to the file, which is going to be written.

Point to note about fputs:
fputs by default doesn’t add new line after writing each record, in order to do that manually – you can have the below statement after each write to the file.

fputs("\n", fpw);

FILE I/O for Binary files

So far, we have learnt file operations on text files, what if the files are binary (such as .exe file). The above programs will not work for binary files, however there is a minor change in handling Binary files. The main difference is the file name & modes. Lets understand this with the help of an example -

Lets say I have two binary files bin1.exe & bin2.exe – I want to copy content of bin1.exe to bin2.exe -

#include <stdio.h>
int main()
{
    char ch;

    /* Pointers for both binary files*/
    FILE *fpbr, *fpbw;

    /* Open for bin1.exe file in rb mode */
    fpr = fopen("bin1.exe", "rb");

    /* test logic for successful open*/
    if (fpbr == NULL)
    {
        puts("Input Binary file is having issues while opening");
    }

    /* Opening file bin2.exe in “wb” mode for writing*/
    fpbw= fopen("bin2.exe", "wb");

    /* Ensure bin2.exe opened successfully*/
    if (fpbw == NULL)
    {
       puts("Output binary file is having issues while opening");
    }

    /*Read & Write Logic for binary files*/
    while(1)
    {
        ch = fgetc(fpbr);
        if (ch==EOF)
             break;
         else
             fputc(ch, fpbw);
     }

     /* Closing both the binary files */
     fclose(fpbr);
     fclose(fpbw);

     return 0;
}

Note: File opening modes are “rb” and “wb” instead of “r” & “w”. Here b tends for binary.

{ 0 comments… add one now }

Leave a Comment

Our Friend's website link : FromDev.com