Files Input and Output

0 vonhopkins10243 November 13, 2020

In this tutorial, we will learn how to perform input and output operations that we can do on the file using a c programming language. We will learn many functions such as fprintf(), fscanf(), fread() etc that helps to handle files. 

We can perform many operations in files such as

  • Creating a File
  • Opening a File
  • Closing a File
  • Reading and Writing a File

Working with File

We should declare a file pointer while working in a file. This declaration is required to communicate between the programs and file.

FILE *fp;

Opening a File:

To open a file, We will use fopen function that is included in stdio.h header file.

The syntax for opening file is

p = fopen("FILE", "mode");

For example

fopen("E:\\c-program\\chp.txt","w");
ModeMeaningIf File does not Exist
rOpen for ReadingReturn NULL by fopen() function
rbOpen for Reading in binary ModeReturn NULL by fopen() function
wOpen for Writingill be created and overwritten if already exist
wbOpen for Writing in binary ModeWill be created and overwritten if already exist
aOpen for appendReturn NULL by fopen() function
abOpen for append in binary ModeWill be created and overwritten if already exist
r+Open for both reading and writingReturn NULL by fopen() function
rb+Open for both reading and writing in binary ModeReturn NULL by fopen() function
w+Open for both reading and writingWill be created and overwritten if already exist
wb+Open for both reading and writing in binary ModeWill be created and overwritten if already exist
a+Open for both reading and appendingWill be created and overwritten if already exist
ab+Open for both reading and appending in binary ModeWill be created and overwritten if already exist

Closing File

We have to close the file operations after reading and writing using fclose() function.

fclose(fp);

Here, fp is the file pointer that linked with the file to be closed.

Reading and Writing to a File

We use functions such as fprintf() and fscanf() for reading and writing to a file.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int num;
   FILE *fptr;

   fptr = fopen("C:\\chp.txt","w");

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

   printf("Enter num: ");
   scanf("%d",&num);

   fprintf(fptr,"%d",num);
   fclose(fptr);

   return 0;
}

This program takes a number from user as input and store in a file chp.txt.

If you compile and run this program then you found the file created in C drive as chp.txt. When you open the file then you can find the number that you have entered.