FILE Processing

Basics of File Handling in C

So far the operations using C program are done on a prompt / terminal which are not stored anywhere. But in software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are:
  1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
  2. Opening an existing file (fopen)
  3. Reading from file (fscanf or fgetc)
  4. Writing to a file (fprintf or fputs)
  5. Moving to a specific location in a file (fseek, rewind)
  6. Closing a file (fclose)
The text in the brackets denotes the functions used for performing those operations.
When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and program.
FILE *fp;
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
The syntax for opening a file in standard I/O is:
fp = fopen("file","Mode")
For Example:
fopen("data.txt","w");

fopen("E:\\algo\\data.txt","r");
ModeDescription
ropens a text file in reading mode
wopens or create a text file in writing mode.
aopens a text file in append mode
r+opens a text file in both reading and writing mode
w+opens a text file in both reading and writing mode
a+opens a text file in both reading and writing mode
rbopens a binary file in reading mode
wbopens or create a binary file in writing mode
abopens a binary file in append mode
rb+opens a binary file in both reading and writing mode
wb+opens a binary file in both reading and writing mode
ab+opens a binary file in both reading and writing mode
Difference between Append Mode(a) and Write Mode(w)
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already present in the file. While in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file.
The file should be closed after reading/writing.
Closing a file is performed using library function fclose().
fclose(fp); //fp is the file pointer associated with file to be closed.
fgetc() function is a file handling function in C programming language which is used to read a character from a file. It reads single character at a time and moves the file pointer position to the next address/location to read the next character. Please find below the description and syntax for each above file handling functions.
fputc() function is a file handling function in C programming language which is used to write a character into a file. It writes a single character at a time in a file and moves the file pointer position to the next address/location to write the next character. Please find below the description and syntax for each above file handling functions.
fgets() function is a file handling function in C programming language which is used to read a file line by line. Please find below the description and syntax for above file handling function.
fputs() function writes string into a file pointed by fp. In a C program, we write string into a file as below.
fputs (fp, “some data”);

Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the structure FILE.

Writing to a text file

Example 1: Write to a text file using fprintf()
#include <stdio.h>
#include <stdlib.h>

int main()
{
   int num;
   FILE *fp;
   fp = fopen("D:\\C++\\FileProcessing\\program.txt","w");

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

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

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

   return 0;
}
This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered.

Reading from a text file

Example 2: Read from a text file using fscanf()
#include <stdio.h>
#include <stdlib.h>

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

   if ((fp = fopen("D:\\C++\\FileProcessing\\program.txt","r")) == NULL){
       printf("Error! Opening file");

       exit(1); // Program exits if the file pointer returns NULL.
   }

   fscanf(fp,"%d", &num);

   printf("Value of n= %d", num);
   fclose(fp); 
  
   return 0;
}
This program reads the integer present in the program.txt file and prints it onto the screen.
If you succesfully created the file from Example 1, running this program will get you the integer you entered.
Other functions like fgetchar()fputc() etc. can be used in similar way.

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

Writing to a binary file

To write into a binary file, you need to use the function fwrite(). The functions takes four arguments: Address of data to be written in disk, Size of data to be written in disk, number of such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Example 3: Writing to a binary file using fwrite()
#include <stdio.h>
#include <stdlib.h>

struct threeNum
{
   int n1, n2, n3;
};

int main()
{
   int n;
   struct threeNum num;
   FILE *fp;

   if ((fp = fopen("D:\\C++\\FileProcessing\\program.bin","wb")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }
   
   printf("Result :\n");
 
   for(n = 1; n < 5; ++n)
   {
      num.n1 = n;
      num.n2 = 5*n;
      num.n3 = 5*n + 100;
      fwrite(&num, sizeof(struct threeNum), 1, fp); 
      printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
   }
   fclose(fp); 
  
   return 0;
}
In this program, you create a new file program.bin in the C drive.
We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main function as num.
Now, inside the for loop, we store the value into the file using fwrite.
The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.
Since, we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fp points to the file we're storing the data.
Finally, we close the file.

Reading from a binary file

Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Example 4: Reading from a binary file using fread()
#include <stdio.h>
#include <stdlib.h>

struct threeNum
{
   int n1, n2, n3;
};

int main()
{
   int n;
   struct threeNum num;
   FILE *fp;

   if ((fp = fopen("D:\\C++\\FileProcessing\\program.bin","rb")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   for(n = 1; n < 5; ++n)
   {
      fread(&num, sizeof(struct threeNum), 1, fp); 
      printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
   }
   fclose(fp); 
  
   return 0;
}
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by *fp into the structure num.
You'll get the same records you inserted in Example 3.
feof() function is a file handling function in C programming language which is used to find the end of a file.
feof functions is used to find the end of a file. In a C program, we use feof() function as below.
feof(fp); //fp – file pointer

    References

  • https://www.programiz.com/c-programming/c-file-input-output
  • https://www.studytonight.com/c/file-input-output.php
  • https://www.tutorialspoint.com/cprogramming/c_file_io.htm
  • https://www.geeksforgeeks.org/basics-file-handling-c/
  • https://fresh2refresh.com/c-programming/c-file-handling/
  • https://www.tutorialspoint.com/c_standard_library/c_function_feof.htm

NIM : 2201755781
Binus.ac.id
Skyconnectiva.com
Nama : Virnando Tan Wijaya

Comments

Popular posts from this blog

Pointers and Arrays

Cloud Computing