C

Examples Of File I/O In C Programming

In this guide, we will learn how to use the C programming language to perform input/output (I/O) operations on a file.

Table of Contents for C File I/O

1. File Opening 2. File Reading
3. Making a File
4. File closure
5. String reading and writing to a file
6. Binary file reading and writing in C
Let’s start with a simple C program before delving into each operation in depth:

A simple C program for opening, reading, and closing files

#include <stdio.h>
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 ("C:\\myfiles\\newfile.txt", "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;
}

In the preceding program, we open the file newfile.txt in r mode, read its contents, and display them on the console. Let’s go over each operation in detail:

1. File opening The fopen() function is used to open a file.

Syntax:

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

pointer_name can be anything you want.
file_name is the name of the file to be opened. Enter the full path here, such as “C:myfilesnewfile.txt.”
You must specify the mode when opening a file. We read a file in “r” mode, which stands for “read only mode.”
for instance:

FILE  *fp;
fp = fopen("C:\\myfiles\\newfile.txt", "r");

The first character’s address is saved in pointer fp.
How can I tell if the file was successfully opened?
If the file does not open successfully, the pointer is set to NULL, so you can write the logic as follows:
This code will determine whether or not the file was successfully opened. If the file does not open, an error message will be displayed to the user.

..
FILE fpr;
fpr = fopen("C:\\myfiles\\newfile.txt", "r");
if (fpr == NULL)
{
    puts("Error while opening file");
    exit();
}

Different File Opening Modes:

The file is opened with the fopen() function, and you can use any of the following modes depending on your needs.
Mode “r”: This is a read-only mode, which means that if the file is opened in r mode, you will not be able to write or modify its content. If fopen() successfully opens a file, it returns the address of the file’s first character; otherwise, it returns NULL.
Mode “w” is a read-only mode. When the specified file does not exist, the fopen() function creates a new file, and if it fails to open the file, it returns NULL.
Mode “a”: This mode allows content to be appended to the end of an existing file. fopen(), like Mode “w,” creates a new file if it does not already exist. If the open fails, it returns NULL.
The File Pointer points to the file’s last character.
Mode “r+”: This mode is identical to mode “r,” but you can perform additional operations on the file opened in this mode. You may read, write, and modify the contents of any file opened in “r+” mode.
The File Pointer points to the file’s first character.
Mode “w+”: Identical to mode “w” except for the operations that can be performed; the file can be read, written, and modified in this mode.
Mode “a+”: The same as mode “a,” you can read and append data in the file, but content modification is not permitted.

2. File Reading

To read the file, we must first open it in any of the modes; for example, if you only want to read it, open it in “r” mode. Certain operations on the file are permitted based on the mode selected during file opening.

C fgetc() is a file reading program:

This function reads the character from the current pointer’s position and moves the pointer to the next character in the file if the read is successful. This function returns EOF when the pointers reach the end of the file (End of File). In our program, we used EOF to determine the end of the file.

#include <stdio.h>
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 ("C:\\myfiles\\newfile.txt", "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;
}

3. Creating a file

To write the file, we must first open it in a writing mode. If you open a file in “r” mode, for example, you won’t be able to write to it because “r” is a read-only mode that only allows reading.

C is an example. The program used to create the file

This program prompts the user for a character and appends that character to the end of the file. If the file does not already exist, this program will create one with the specified name and write the input character into it.

#include <stdio.h>
int main()
{
   char ch;
   FILE *fpw;
   fpw = fopen("C:\\newfile.txt","w");

   if(fpw == NULL)
   {
      printf("Error");   
      exit(1);             
   }

   printf("Enter any character: ");
   scanf("%c",&ch);

   /* You can also use fputc(ch, fpw);*/
   fprintf(fpw,"%c",ch);
   fclose(fpw);

   return 0;
}

4. File closure

The fclose() function is used to close a file that has been opened. You must provide a pointer to the file you want to close as an argument.

An example of how to open, read, write, and close in 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("C:\\file1.txt", "r");

    /* Ensure FILE1.C opened successfully*/
    if (fpr == NULL)
    {
         puts("Input file cannot be opened");
    }

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

    /* Ensure FILE2.C opened successfully*/
    if (fpw == NULL)
    {
       puts("Output file cannot be opened");
    }

    /*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 and Write Strings in Files Using fgets and fputs

We’ll go over how to read and write strings to a file in this section.

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

s: A character array used to store strings.
rec len: The input record’s length.
fpr: The input file’s pointer.
Consider the following example:

In C programming, an example of reading strings from a file

#include <stdio.h>
int main()
{
    FILE *fpr;
    /*Char array to store string */
    char str[100];
    /*Opening the file in "r" mode*/
    fpr = fopen("C:\\mynewtextfile.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;
}

In the preceding example, we used the fgets function as follows:

fgets(str, 10, fpr)

The string (array of chars) in which you are storing the string after reading it from file is represented by str.
The length of the string that must be read each time is 10.
fpr is a pointer to the file that will be read.
Why did I use if(fgets(str, 10, fpr)==NULL as a logic to determine the file’s end?
In the preceding examples, we used ch==EOF to determine the end of the file. This logic was used because fgets returns NULL when no more records are available to be read.

Writing a string to a file in C

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

char *s – Array of characters
FILE *fpw – A pointer (of the FILE type) to the file that will be written.

#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*/
     fpw = fopen("C:\\mynewtextfile2.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 – 
      * mynewtextfile2.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 is the name of the array in which string is stored.
fpw – FILE A pointer to the output file into which the record should be written.

A note about fputs: by default, fputs does not add a new line after writing each record; to do so manually, use the following statement after each write to the file.

fputs("\n", fpw);

For binary files, use C FILE I/O.

We’ve only learned file operations on text files so far; what if the files are binary? (such as .exe file). The above programs will not work with binary files, but there is a minor difference in how binary files are handled. The main distinction is the file name and modes. Let’s look at an example to better understand this. Assume I have two binary files named bin1.exe and bin2.exe, and I want to copy the contents of bin1.exe to bin2.exe:

Example: Binary File Reading and Writing in C

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

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

    /* Open for bin1.exe file in rb mode */
    fpbr = 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”..

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button