• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

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

Aniruddha Chaudhari/33231/4
C / C++Code

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!

Codecpp
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Pat Anablak
    April 27, 2017 at 9:51 pm

    Programming is an art.

    • Reply
      Aniruddha Chaudhari
      March 9, 2019 at 11:26 am

      Indeed! Thanks!

  • Reply
    shaim kibria
    August 20, 2020 at 3:39 pm

    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;
    }
    
    • Reply
      Aniruddha Chaudhari
      August 21, 2020 at 6:50 pm

      Can you share your exact output?

Leave a Reply Cancel reply

C Programming

  1. C- Introduction
  2. C- Compile & Execute Program
  3. C- Data Types
  4. C- if-else statement
  5. C- While, do-while, for loop
  6. C- Array
  7. C- Function (Types/Call)
  8. C- strlen() vs sizeof()
  9. C- Nested Switch Statement
  10. C- Recursion
  11. C- Dynamic Programming
  12. C- Storage Classes
  13. C- Creating Header File
  14. C- Null Pointer
  15. C- Stack and Queue
  16. C- Implement Stack using Array
  17. C- Implement Linked List in C
  18. C- File Handling
  19. C- Makefile Tutorial

Object Oriented Concepts in C++

  • C++: C vs OOPs Language
  • C++: Introduction to OOPs Concepts
  • C++: Inheritance

Sorting Algorithms

  • Different Types of Sorting Algo
  • Selection Sort
  • Bubble Sort
  • Quick Sort

Programming for Practice

  1. Online C/C++ Compiler

String Handling:

  1. Remove White Spaces from String
  2. Implement strstr Function in C
  3. Convert String to Int – atoi()
  4. Check if String is Palindrome
  5. Check if Two Strings are Anagram
  6. Split String in using strtok_r()
  7. Undefined reference to strrev

Array:

  1. Check if Array is Sorted

Bit Manipulation:

  1. Count Number of 1’s in Binary

Linked List:

  1. Reverse a Linked List Elements

Number System:

  1. Program to Find 2’s Complement
  2. Convert Decimal to Binary in C

Tricky Questions:

  1. Add Two Numbers without Operator
  2. Find Next Greater Number
  3. Swap values without temp variable
  4. Print 1 to 100 without Loop

Interview Coding Questions

  • 50+ Interview Coding Questions

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard