Files I/O in C: Open, Read, Write & Close file with Examples

Files I/O in C: Open, Read, Write & Close file with Examples

Files I/O in C – This tutorial will teach you how to use the C programming language to execute input/output (I/O) operations on a file.

The standard input and output devices supported by the C programming language were described in the last chapter. This chapter explains how to create, open, and close text or binary files for data storage in C programs.

Whether a file is a text file or a binary file, they both represent a sequence of bytes. The C programming language gives you access to both low-level (OS level) calls and high-level functions to manage files on your storage devices. You will learn about the crucial calls for file management in this chapter.

Library Management System In C With...
Library Management System In C With Source (Free Download) 2022

You must test the C Language code provided in this lesson in your code editor to validate it. However, if you prefer to execute this code online, we also provide a free C Online Compiler for testing your C Language code.

Opening Files in C

The fopen() method can be used to open an existing file or to create a new one. An object of type FILE that contains all the data required to control the stream will be initialized by this method. The following is the prototype for this function call:

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

Here, access mode can be any of the following settings, and filename is a string literal that you will use to name your file.

ModeDescription
rOpensa text file that is already available for reading.
wOpensa writing text file. If it doesn’t already exist, a new file is made. In this case, your software will begin writing content at the file’s beginning.
aOpensa text document used for appending mode writing. If it doesn’t already exist, a new file is made. Here, your program will begin adding content to the already-existing file.
r+Opensa text file that can be read and written in.
w+Opens
a text file that can be read and written in. If the file already exists, it is first truncated to zero length; if not, a new file is created.
a+Opensa text file that can be read and written in. If the file doesn’t already exist, it is created. Writing can only be added at the end; reading will begin at the beginning.

Use the following access modes in place of the ones listed above if you’re handling binary files.

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Why files are needed?

  • The entire set of data is lost when a program is stopped. Your data will be kept even if the program is terminated if you store it in a file.
  • It will take a long time to enter all the data if there are a lot of them.
  • However, if you have a file with all the data in it, you can quickly access the data using a few C commands.
  • Without making any changes, you can transfer your data from one machine to another with ease.

Types of Files in C

There are two types of files you should be aware of while working with them:

  • Text files
  • Binary files

Text files

The typical.txt files are text files. Text files can be simply created using any straightforward text editor, such Notepad.

You can view the entire file’s contents as plain text when you open those files. Editing and deleting the contents is simple.

They require the least maintenance, are readily readable, offer the least security, and require more storage space.

Binary files

The majority of the bin files on your computer are binary files.

They store information in binary form (0s and 1s) rather than plain text.

They offer stronger security than text files, can carry more data, and cannot be read easily.

File Operations in C Program

Four major operations are available in C for text or binary files:

  • Creating file
  • Opening existing file
  • Closing file
  • Reading from and writing information to a file

Closing a File in C

Use the fclose() method to close a file. This function’s prototype is:

int fclose( FILE *fp );

When the file is successfully closed, the fclose(-) function returns zero, or EOF if there was a problem. This function really closes the file, releases any memory used for the file, and flushes any data that is still pending in the buffer to the file. The header file stdio.h contains a definition for the constant EOF.

The C standard library has a number of functions that allow you to read and write files either character per character or as fixed length strings.

After reading or writing, the file should be closed, both the text and binary versions.

The fclose() method is used to close a file.

fclose(fptr);

After reading or writing, the file should be closed, both the text and binary versions.

The fclose() method is used to close a file.

Create a File in C

The simplest method to add individual characters to a stream is as follows:

int fputc( int c, FILE *fp );

The output stream referred to by fp receives the character value of the input c from the function fputc(). If there is a success, it returns the written character; if there is a failure, it returns EOF. The following functions can be used to add a null-terminated string to a stream.

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

The string s is written by the function fputs() to the output stream referred to by fp. If it is successful, it returns a non-negative value; if there is a problem, it returns EOF. To write a string into a file, use the int fprintf(FILE *fp,const char *format,…) function. Try the example below.

Ensure that /tmp directory is accessible. If not, you must first create this directory on your computer before continuing.

Example 1 of Create a File in C

#include <stdio.h>
int main() {
   FILE *fp;
   fp = fopen("/tmp/tutorial.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}

When the example code is compiled and run, two lines utilizing two separate functions are written in a new file called tutorial.txt in the /tmp directory. In the section after this, let’s read this document.

Read a File in C

The simplest function to read one character from a file is provided below.

int fgetc( FILE * fp );

A character is read using the fgetc() method from the input file referred to by fp. The character read or EOF is returned as the return value in the event of an error. The function that follows enables reading of a string from a stream:

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

The fgets() function reads n-1 characters at a time from the input stream that fp is referencing. It adds a null character to the end of the read string and copies it into the buffer buf.

The function only returns the characters read up to that point, including the new line character, if it runs across a newline character (‘n’) or the end of the file (EOF) before reading the maximum number of characters.

Alternatively, you can read strings from a file using the int fscanf(FILE *fp, const char *format,…) function, however it stops reading after the first space character.

Example 2 of Read a File in C

#include <stdio.h>
main() {
   FILE *fp;
   char buff[255];
   fp = fopen("/tmp/example.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);
}

Let’s examine this incident a little more closely. The first call was for fscanf(), which read only This since there was a space after that. The second call was for fgets(), which read the remaining line until it reached the end of the line. The final call to fgets() fully reads the second line.

Opening Modes in Standard I/O in C

ModeMeaning of ModeDuring Inexistence of file
rOpen for reading.If the file does not exist, fopen() returns NULL.
rbOpen for reading in binary mode.If the file does not exist, fopen() returns NULL.
wOpen for writing.If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wbOpen for writing in binary mode.If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
aOpen for append.
Data is added to the end of the file.
If the file does not exist, it will be created.
abOpen for append in binary mode.
Data is added to the end of the file.
If the file does not exist, it will be created.
r+Open for both reading and writing.If the file does not exist, fopen() returns NULL.
rb+Open for both reading and writing in binary mode.If the file does not exist, fopen() returns NULL.
w+Open for both reading and writing.If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb+Open for both reading and writing in binary mode.If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
a+Open for both reading and appending.If the file does not exist, it will be created.
ab+Open for both reading and appending in binary mode.If the file does not exist, it will be created.

Reading and writing to a binary file in C

In the case of binary files, the functions fread() and fwrite() are used to read from and write to a file on the disk, respectively.

Writing to a binary file in C Language

To write to a binary file, the fwrite() function must be used. Each function requires four arguments:

  • The disk address of data to be written
  • Data size to be written to the disk
  • number of such data types
  • pointer to the file you wish to write to.
fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3 in Write to a binary file using fwrite() in C Language

#include <stdio.h>
#include <stdlib.h>
struct threenumbers
{
   int number1, number2, number3;
};
int main()
{
   int x;
   struct threenumbers numbers;
   FILE *fptr;
   if ((fptr = fopen("C:\\tutorial.bin","wb")) == NULL){
       printf("Error! opening file");
       // Program exits if the file pointer returns NULL.
       exit(1);
   }
   for(x = 1; x < 5; ++x)
   {
      numbers.number1 = x;
      numbers.number2 = 5*x;
      numbers.number3 = 5*x + 1;
      fwrite(&numbers, sizeof(struct threenumbers), 1, fptr); 
   }
   fclose(fptr); 
  
   return 0;
}

In this program, a new file program is created. bin located on the C disk on your computer or laptop.

In the main function, we declare a structure containing three numbers, number1, number2, and number3, and define it as num.

Now, within the for loop, we store the value using fwrite ().

The first parameter is the address of the variable num, while the second parameter is the size of the structure threenumbers.

Since only one instance of numbers is being inserted, the third parameter is 1. And the final parameter *fptr specifies the file in which the data will be stored.

We then close the file.

Reading from a binary file

Similar to the fwrite() method, fread() likewise accepts four arguments.

fread(addressData, sizeData, numbersData, pointerToFile);

Example 4 in Read from a binary file using fread() in C Program

#include <stdio.h>
#include <stdlib.h>
struct threeNumbers
{
   int number1, number2, number3;
};
int main()
{
   int x;
   struct threeNumbers numbers;
   FILE *fptr;
   if ((fptr = fopen("C:\\tutorial.bin","rb")) == NULL){
       printf("Error! opening file");
       // Program exits if the file pointer returns NULL.
       exit(1);
   }
   for(x = 1; x < 5; ++x)
   {
      fread(&numbers, sizeof(struct threeNumbers), 1, fptr); 
      printf("n1: %d\tn2: %d\tn3: %d\n", numbers.number1, numbers.number2, numbers.number3);
   }
   fclose(fptr); 
  
   return 0;
}

This software reads the same file, tutorial.bin, looping over each record individually.

Simply put, you read one threeNumbers record of threeNumbers size into the structure number from the file pointed to by *fptr.

You will receive the identical records that you inserted in Example 3.

Getting data using fseek() in C

If a file has numerous records and you need to retrieve one at a given place, you must loop through all the entries before it.

This will be a major memory and processing time waste. Fseek(). can be used to access the necessary data in a simpler manner

Fseek(), as the name implies, moves the cursor to the specified record in the file.

Syntax of fseek() in C

fseek(FILE * stream, long int offset, int whence);

The file pointer is the first parameter stream. The second parameter determines where the record needs to be located, and the third parameter designates where the offset should begin.

Different whence in fseek() in C Program

WhenceMeaning
SEEK_SETstarts the offset at the file’s beginning.
SEEK_ENDstarts the offset at the file’s end.
SEEK_CURstarts the offset at the point in the file where the pointer is currently located.

Example 5 of fseek() in Program

#include <stdio.h>
#include <stdlib.h>
struct tutorials
{
   int tutorial1, tutoria2, tutoria3;
};
int main()
{
   int tut;
   struct tutorials number;
   FILE *fptr;
   if ((fptr = fopen("C:\\tutorial.bin","rb")) == NULL){
       printf("Error! opening file");
       // Program exits if the file pointer returns NULL.
       exit(1);
   }
   
   // Moves the cursor to the end of the file
   fseek(fptr, -sizeof(struct tutorials), SEEK_END);
   for(tut = 1; tut < 5; ++tut)
   {
      fread(&number, sizeof(struct tutorials), 1, fptr); 
      printf("n1: %d\tn2: %d\tn3: %d\n", number.tutorial1, number.tutoria2, number.tutoria3);
      fseek(fptr, -2*sizeof(struct tutorials), SEEK_CUR);
   }
   fclose(fptr); 
  
   return 0;
}

The records from the file program will begin to be read by this program. bin from last to first in reverse, then prints it.

Summary

  • Data is kept in memory spaces called files.
  • Programming in “C” offers a number of functions for working with files.
  • File management refers to the process of altering files.
  • A file must be opened in order to be operated on.
  • You can open a file in read-only, write-only, or append-only mode.
  • To read and write a single character, use the getc and putc methods.
  • The fscanf() method allows you to read and parse data from a file.
  • By looping through the file until the EOF is reached, we may read a full file using the getc function.
  • Using the function fprintf(), we can write to a file after defining its name. The string text must have the newline character at the end of it.

Your 15 seconds will motivate us to put forth even more effort.

Inquiries

If you have any questions or suggestions about Files I/O in C: Open, Read, Write & Close file with Examples, please feel free to leave a comment below.

About Next Tutorial

In the next following post, I’ll create a Preprocessors in C and try to explain its many components in full details. I hope you enjoy this post on Files I/O in C: Open, Read, Write & Close file with Examples, in which I attempt to illustrate the language’s core grammar.


Leave a Comment