Step-By-Step Reading And Writing Files in C Program

Step-By-Step Reading And Writing Files in C Program

Step-By-Step Reading And Writing Files in C Program

The file is important to store data on the computer. This data can be anything. Save it and use it whenever you need.

Here, we are interested in a text file where we can read and write any string/text inside the file.

I am going to demonstrate you reading and writing files in C program with an example. You don’t need to mug up the code if you follow and understand each step described in this post.

So let’s begin.

Reading And Writing Files in C Program:

File handling in C programming includes the following operations.

  • Open the file.
  • Read the file.
  • Write the file.
  • Close the file.

Reading Files in C Program

Before reading the file using programming, just create a text file in the current directory and add some text in a file using simple notepad.

Follow the steps to read the file:

  • Create a file pointer.
    File * fpReadFile;
  • To read any file, you have to open the text file using file pointer.
    fpReadFile = fopen("sampleFile.txt", "r");
  • Run a loop until it reaches EOF (end of file). Now read each character from the file using getc() function.
    while ((c = getc(fpReadFile)) != EOF)
    putchar(c);
  • Once reading completed, close the file.
    fclose(fpReadFile);

Note: If you don’t have a text file to read, fopen() will return NULL.

Here is a simple C program to read a file.

#include<stdio.h>

int main()
{
  int c;
  FILE *fpReadFile;
  fpReadFile = fopen("sampleFile.txt", "r");
  printf("\n");
  if(fpReadFile)
  {
    printf("\nReading File...\n\n");
    while ((c = getc(fpReadFile)) != EOF)
    putchar(c);
    fclose(fpReadFile);
  }
  else
  {
    printf("\nError: Unable to open the file for Reading.");
  }
  return 0;
}

The output of the Program:

Reading And Writing Files in C Program Output

In another way, you can open the file in append “a” mode. In this mode, if you have don’t have a text file to read, it will create a new text file with the given name in the current directory.

Writing Files in C Program

The stepwise explanation for writing the file:

  • As like steps in reading the file, create a file pointer.
    File * fpWriteFile;
  • Open the File. Here you have to open the file in writing “w” mode.
    fpWriteFile = fopen("sampleFile.txt", "w");
  • Write the text in a file.
    fprintf(fpWriteFile,"\nProgramming is a art.");
  • Close the file.
    fclose(fpWriteFile);

Here is a program in C to write the file.

#include<stdio.h>

int main()
{
  FILE *fpSample;
  fpSample = fopen("sampleFile.txt", "w");
  if(fpSample)
  {
    fprintf(fpSample,"Programming is a art.\nLlearn it.\n");
    fclose(fpSample);
  }
  else
  {
    printf("\nError: Unable to open the file for Writing.");
  }
}

Remember whenever you open file in “w” mode, it overwrites the code.

Appending Content to the File:

To avoid overwriting, open file in “a” mode. It appends newly contents.

Best Practice to follow while writing a program for file handling:

  • Always close the file after using it.
  • Handle all the file handling error cases such as error while opening/reading/writing file. Apply if and else statement gracefully. It is easy while debugging.

In the above codes, if you get the output like “Error: Unable to open the file for Reading” or “Error: Unable to open the file for Reading”, no worry. This is mostly because the file that you want to read or write is not present in the current directory/folder. So just ensure if the file is present in the same folder where your program file is present.

Reading and Writing Files in C Program is not much difficult as it seems if you understand and follow the steps carefully.

If you have any doubt about file handling in C, please ask in the comment section.

Happy Programming!

4 Comments

  1. output is showing :Error opening file

    //3.2 Write a program to copy some parts of the file and write to another file.

    //GETTING DESIRED OUTPUT

    #include
    #include
    int main()
    {
        FILE *fptr, *fp1, *fp2, *fp3, *fp4, *fp5;
        char c;
    
        if ((fptr = fopen("F:\CS251\program3\folder a\a.txt", "r"))==NULL)
        {
            printf("\nError opening file!"); // Program exits if the file pointer returns NULL.
            exit(1);
        }
    
        fp1 = fopen("F:\CS251\program3\folder a\A1.txt","w");
        while((c=fgetc(fptr))!='&amp;')
        {
            fputc(c,fp1);
        }
        //printf("\nPage 1 copied from a.txt to A1.txt");
        fclose(fp1);
    
    
        fp2 = fopen("F:\CS251\program3\folder a\A2.txt","w");
        while((c=fgetc(fptr))!='&amp;')
        {
            fputc(c,fp2);
        }
        //printf("\nPage 2 copied from a.txt to A2.txt");
        fclose(fp2);
    
    
        fp3 = fopen("F:\CS251\program3\folder a\A3.txt","w");
        while((c=fgetc(fptr))!='&amp;')
        {
            fputc(c,fp3);
        }
        //printf("\nPage 3 copied from a.txt to A3.txt");
        fclose(fp3);
    
    
        fp4 = fopen("F:\CS251\program3\folder a\A4.txt","w");
        while((c=fgetc(fptr))!='&amp;')
        {
            fputc(c,fp4);
        }
        //printf("\nPage 4 copied from a.txt to A4.txt");
        fclose(fp4);
    
    
        fp5 = fopen("F:\CS251\program3\folder a\A5.txt","w");
        while((c=fgetc(fptr))!='&amp;')
        {
            fputc(c,fp5);
        }
        //printf("\nPage 5 copied from a.txt to A5.txt");
        fclose(fp5);
    
        printf("\nAll pages have been copied !!");
        fclose(fptr);
        return 0;
    }
    

Leave a Reply

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