Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

What are different ways of reading and writing from and to files?

Aymen Bashir

We will discuss reading from and writing to for two types of files:

  • Text files
  • Binary files

Text files

Text files are files with the extension .txt. The content of text files is simple text and one can easily edit text files in any text editor.

Writing to text files

The function fprintf() is used to write to a text file. The function is similar to printf(), except that fprintf() takes a pointer to the file where we want to write.

The code below illustrates writing to a text file using fprintf():

#include <stdio.h>

int main()
{
   int number = 10;
   FILE *fileptr;
   fileptr = fopen("sample.txt","w");
   fprintf(fileptr,"%d",number);
   fclose(fileptr);

   return 0;
}
  • Line 1 includes the <stdio.h> header where our functions for reading and writing from files are present.
  • Line 6 defines a pointer fileptr of type FILE, which is a pointer type that helps the program communicate with the files.
  • The fopen() function in Line 7 takes a file name or address and opens it in the mode specified, which in our case is the write mode, specified by the argument w. If the function fails to locate the file, then it creates a new file and returns a pointer to that file.
  • The fprintf function in Line 8 simply writes the number 10 in the file sample.txt. The address of the file is given by fileptr, which is passed to the fprintf function. After we are done writing to the file, we can close it by passing fileptr to fclose() function that frees the pointer fileptr.

Reading from text files

We will discuss three functions to read from the text files:

fscanf()

The function fscanf() is used to read from a text file in the same way as we use scanf(). The only difference is that we need to pass the file pointer to the fscanf() function.

int fscanf(FILE *stream, const char *format, ...)

fscanf() reads from the FILE that stream is pointing towards.

The code below illustrates reading a number from a text file:

main.c
sample.txt
#include <stdio.h>

int main()
{
   int number;
   FILE *fileptr;
   fileptr = fopen("sample.txt","r");
   fscanf(fileptr,"%d", &number);
   printf("File content = %d", number);
   fclose(fileptr); 
   return 0;
}
  • Line 1 includes the <stdio.h> header where our functions to read and write from files are present.
  • Line 6 defines a pointer fileptr of type FILE, which is a pointer type that helps the program communicate with the files.
  • The fopen() function in Line 7 takes a file name or address and opens it in the read mode specified by the argument r. It returns a pointer to the file.
  • The fscanf function in Line 8 simply reads the number in the file sample.txt and stores it in the integer type variable number. The address of the file is given by fileptr, which is passed to the fscanf function. After we are done reading the file, we can close it by passing fileptr to fclose() function that frees the pointer fileptr.

Other functions to read from a text file are fgetc() and fgets().

fgetc()

The function fgetc() gets the next character from the specified stream and increments the pointer for the stream.

fgetc(FILE *stream)

We can read the complete text in the file if we call the function in the loop until the pointer in the stream points to the end of file.

Try out the code below and observe how the content of sample.txt file is read and printed on the console:

main.c
sample.txt
#include <stdio.h>

int main () {
   FILE *fileptr;
   char c;
   fileptr = fopen("sample.txt","r");
   do {
      c = fgetc(fileptr);
      if( feof(fileptr)) {
         break ;
      }
      printf("%c", c);
   } while(1);

   fclose(fileptr);
   return(0);
}

The code above opens the sample.txt file and uses the fgetc() function to loop through all the characters in the file while printing them. The if statement checks if the pointer fileptr points to the end of file. When the condition is met, the loop breaks.

fgets()

The function fgets() reads a line from the specified stream and stores it into the string pointed to by str. It stops reading when either (n-1) characters are read, the newline character is read, or the end of file is reached.

char * fgets(char *str, int n, FILE *stream)

The pointer str points towards the address where data will be read into, n specifies the maximum number of characters that can be read, and stream points towards the file to be read from.

This is indicated below:

main.c
sample.txt
#include <stdio.h>

int main () {
   FILE *fileptr;
   char str[80];
   fileptr = fopen("sample.txt","r");
   fgets (str, 80, fileptr);
   printf("%s", str);
   fclose(fileptr);
   return(0);
}

In the sample.txt file, we can see that there are two lines of text but the fgets() function only reads the first line. This is because it stops reading once a newline character is reached.

Binary files

Binary files are files with the extension .bin. As evident from the name, they store data in the form of binary digits, i.e., 0s and 1s.

Reading and writing to Binary files

For binary files, the functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively.

fwrite()

The function fwrite() returns the number of characters written in a file. It has the following syntax:

fwrite(void *ptr, dataSize, dataNumbers, FILE *stream); 

where

  • ptr is address of the data to be written on the disk.
  • dataSize is size of each element to be written in the disk, often specified using sizeof() operator.
  • dataNumbers is number of elements, each one with the size of dataSize.
  • stream pointer points towards the file where data will be written.

fread()

The function fread() also takes the same arguments as the function fwrite(). It returns the numbers of items read.

fread(void *ptr, dataSize, dataNumbers, FILE *stream)
  • ptr is the address of the block of memory where data will read into.
  • dataSize is the size of each element to be read, often specified using the sizeof() operator.
  • dataNumbers is the number of elements, each one with a size of dataSize.
  • stream is the pointer to the file from where data has to be read.

RELATED TAGS

CONTRIBUTOR

Aymen Bashir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring