Table of contents
1.
Introduction
2.
Opening Files
3.
Reading a File
4.
Writing a File
5.
Closing a File
6.
FAQs
7.
Key Takeaways: 
Last Updated: Mar 27, 2024

File I/O

Author NISHANT RANA
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A file is a space in the memory where we can store the data. A file can be a text file or a binary file. It always represents a sequence of bytes. Whenever a program terminates(reasons can be electricity cut, system shut down, etc.), the entire data gets lost. We can protect our data from getting lost by storing it in the file. We can treat files as a container to store our data.

Recommended Topic, Sum of Digits in C, C Static Function.

Let us now see various operations we can perform on a File.

Opening Files

In order to create a new file or open any of the existing files, we can use the fopen() function. Calling this function will create an object of the type FILE. This object would contain all the necessary information to control the stream of data. 

Syntax:-

FILE *fopen( const char * filename, const char * mode );

fileName: It is a String literal that specifies the file name.

mode: It is a mode of access. There are different types of modes as listed below.

S. No. Mode Description
1 r This mode is used to open a file for reading the data.
2 w This mode is used to open a file and write data to it. If no such file exists, then a new file is created. It starts writing the data from the beginning of the file.
3 a This mode is used to open a file and write the data to it in an appending mode. If no such file exists, then a new file is created. It starts appending the new data to the old data of the file.
4 r+ This mode is used to open a file for both reading and writing of data.
5 w+ This mode is used to open a file for both reading and writing of data. It truncates the files to zero length if it exists, else creates a new file.
6 a+ This mode is used to open a file for both reading and writing. It creates a new file if it does not exist. It reads from the starting and appends(write) to the end of the old data of the file.

 

All of the above modes are used to access a text file.

Modes used to access a Binary file with the same functionalities are:-

  1. rb
  2. wb
  3. ab
  4. rb+
  5. r+b
  6. wb+
  7. w+b
  8. ab+
  9. a+b

Reading a File

We can read a character from the file using the fgetc() function.
Syntax:

int fgetc( FILE * fp );

The return value of this function is the character read. In case of any error, it returns EOF.

We can read a line from a stream of characters using the fgets() function.

Syntax:

char *fgets( char *buf, int n, FILE *fp );

This function reads the n-1 character from the stream referenced by fp. It reads the string and appends the string to the buffer buf. It also appends a null character at the end to terminate the string.

If the fgets() function, reach a newline character ‘/n’ or EOF(End of the File) before reading the maximum number of characters, then it returns the characters read till now along with the newline character.


We can also use the fscanf() function to read a line. The main problem with this function is that it stops reading the characters as soon as it encounters a white space.

Syntax:

fscanf(FILE *fp, const char *format, ...)

Sample Code

#include <stdio.h>


main() {

   FILE *fp;
   char buff[255];


   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1: %s\n", buff );


   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);
}

Output:

1: This
2: is testing for fprintf...
3: This is testing for fputs…

Writing a File

We can write an individual character to the file using the fputc() function.

Syntax: 

int fputc( int c, FILE *fp );

This function writes the character value of the argument c in the output stream referenced by fp. It returns the character written by it. In case of an error, it returns EOF. 

 

We can use the fputs function to write the null-terminated string to a stream.

Syntax:

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

This function writes the String to the output stream referenced by fp. It returns a non-negative value after successful writing. In case of an error, it returns EOF.

Sample Code

#include <stdio.h>


main() {
   FILE *fp;


   fp = fopen("/tmp/test.txt", "w+");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}

After running the above code, a new file(test.txt) is created in the /tmp directory. Then a line is written in the file using the fputs() function.

Closing a File

We can close a file using the fclose() function.

Syntax:

int fclose( FILE *fp );

This function returns 0 on success. If any error occurs then it returns EOF. The data pending in the buffer is added to the file. After that, the file is closed and the memory allocated to the file is released.

Also see, Tribonacci Series and Short int in C Programming

FAQs

  1. What is a file?
    A file is a space in the memory where we can store the data. A file can be a text file or a binary file.
     
  2. What is the problem with fscanf() function to read a file?
    The main problem with this function is that it stops reading the characters as soon as it encounters a white space. Hence, it does not read the white spaces.

Key Takeaways: 

In this article, we have extensively discussed the following things:

  1. We first discussed what are files.
  2. Then we discussed various operations, we can perform on a file.

We hope that this blog has helped you enhance your knowledge regarding Files I/O in C language and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!


Live masterclass