17.10 – Formatted text files – Writing and Reading

by subbu on October 14, 2014

So far we have worked with unformatted text files that are the text files with no format. These types of files are generally used to store the documents, letters and specifications which follow paragraph format.

Other type of files are formatted files where the data is stored in a tabular format that is in rows and columns where every row has the details of a single entity and columns of a particular row has the details (attributes) of that entity. These are the most commonly used files in database related applications

formatted text file

Now in this session we will see how we can write and read formatted text files using fprintf() and fscan()

Writing formatted text on to the file:

fprintf() function

It works similar to printf() function but writes on to the file rather console output. It takes three arguments that are the file pointer, format string and the list of variables. The list of values of variables would be printed on to the file as per the format string.

fprintf() function in C language

It returns the size of data that was written on to the file, returns -1 if any thing goes wrong in writing on to the file.

Now we will go through an example where the program accepts the details of “n” products from the keyboard and stores on to the file “product”

FILE *p;
p=fopen("product","w");

It opens the file in write mode

printf("Product Code:");
scanf("%d",&pcode);
printf("Product Name:");
scanf("%s",pname);
printf("Price:");
scanf("%f",&price);
printf("Quantity:");
scanf("%d",&qty);

The above code accepts the details of a product from the keyboard and stores into the local variables pcode, pname, price and qty.

tot=price*qty;

Here total is calculated

fprintf(p,"%d\t%s\t%f\t%d\t%f\n",pcode,pname,price,qty,tot);

It prints the details of a product onto the file “product” through the file pointer “p”

We can accept the details of “n” product from the keyboard and write onto the file “product” using a loop

for(i=1;i<=n;i++)
{
 /* Accepting details from the keyboard */
 printf("Product Code:");
 scanf("%d",&pcode);
 printf("Product Name:");
 scanf("%s",pname);
 printf("Price:");
 scanf("%f",&price);
 printf("Quantity:");
 scanf("%d",&qty);
 /* calculating total */
 tot=price*qty;
 /* printing on to the file */
 fprintf(p,"%d\t%s\t%f\t%d\t%f\n",pcode,pname,price,qty,tot);
}

writing on to formatted text file

Putting altogether as a program

#include<stdio.h>
int main()
{
 int pcode,qty,n,i;
 float price,tot;
 char pname[20];
 FILE *p;
 p=fopen("product","w");
 printf("How many products? ");
 scanf("%d",&n);
 printf("Enter the details of %d products:\n",n);
 for(i=1;i<=n;i++)
 {
   printf("\nPcode:");
   scanf("%d",&pcode);
   printf("Product Name:");
   scanf("%s",pname);
   printf("Price:");
   scanf("%f",&price);
   printf("Quantity:");
   scanf("%d",&qty);
   tot=price*qty;
   fprintf(p,"%d\t%s\t%f\t%d\t%f\n",pcode,pname,price,qty,tot);
 }
 printf("1 file created..");
 fclose(p);
 return 0;
}

Execution:
How many products? 2
Enter the details of 2 products:

Pcode:1000
Product Name:Lux
Price:45.25
Quantity:4

Pcode:1001
Product Name:Fiama
Price:62.00
Quantity:5

1 file created..

Reading from the formatted text file

fscanf() function

It is similar to the function scanf() but the difference is that, It fetches records row by row from the formatted text file and stores into the specified variables as per the format specifier

It accepts the file pointer, format string and the list of addresses of variables as arguments, read the record from the file through the file pointer and stores into the specified variables in a sequence.

fscanf() in C language

It returns the size of data that was fetched from the file and returns -1 if any thing goes wrong in reading the file.

feof() function

In case of unformatted text file we can find the end of file using either -1 or EOF. So we can read the file as long as EOF won’t come.

if(ch==-1) /* finding end of file for unformatted file */
  break;

While reading the data from a formatted file we can’t find the end of file using either EOF or -1 because here we are accessing the file record by record rather character by character. There is an another way of finding end of file of a formatted file that is by using feof() function.

feof() function accepts the file pointer as argument, returns 0 (false) as long as fetching of records is successful and returns a non-zero (true) on reaching the end of file

feof() function in C language

while(1)
{
 --------
 if(feof(p))
   break;
 --------
}

The above loop would continue as long as no end of file is reached because feof(p) returns 0 when last fetch of record was successful. So loop would not break as long as feof(p) returns 0, only breaks when last fetch was not successful and feof(p) returns a non-zero.

Now we will see how we can read formatted text from the file “product” that was created in previous session

FILE *p;
p=fopen("product","r");

It opens the file in read mode

fscanf(p,"%d%s%f%d%f",&pcode,pname,&price,&qty,&tot);

It fetches a record from the file “product” through the file pointer “p” and stores into the specified variables.

To fetch all the records one by one from the file “product” and print the details onto the console, we can use a loop that breaks only when end of file is reached

while(1)
{
 fscanf(p,"%d%s%f%d%f",&pcode,pname,&price,&qty,&tot);
 if(feof(p))
   break;
 printf("%d\t%s\t%f\t%d\t%f\n",pcode,pname,price,qty,tot);
}

Let us put all together as a program

#include<stdio.h>
int main()
{
 int pcode,qty;
 float price,tot,bill=0;
 char pname[20];
 FILE *p;
 p=fopen("product","r");
 printf("               Bill\n");
 printf("---------------------------------------\n");
 while(1)
 {
   fscanf(p,"%d%s%f%d%f",&pcode,pname,&price,&qty,&tot);
   if(feof(p))
     break;
   printf("%d\t%s\t%f\t%d\t%f\n",pcode,pname,price,qty,tot);
   bill=bill+tot;
 }
 printf("               Toal Bill: %f",bill);
 fclose(p);
 return 0;
}

Execution
Bill
—————————————
1000   Lux       45.250000       4       181.000000
1001   Fiama   62.000000      5       310.000000
Toal Bill: 491.000000

Previous post:

Next post: