facebook like button

04 June, 2011

program 55: reading a file in C

The need:
 In previous post we wrote some data to a file. This program will read that data and print on the output screen. So this program is only a rehearsal of reading a file during more complex programs.

The code:
-------------------------------------------- 
#include<stdio.h>
#include<stdlib.h>
#define ITEMS 1
main()
{
    FILE *fp;
    int number,quantity,i;
    float price, value;
    char item[10],filename[20];
    printf("Enter file name in which you have your data. => ");
    gets(filename);
    fp=fopen(filename,"r");
    if(!fp)
    {
        printf("No such file found. Exiting..\n");
        exit(0);
    }
    printf("Item_name\tnumber\tprice\t      quantity\tvalue\n");
    for(i=0;i<ITEMS;i++)
    {
        fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
        value=price*quantity;
        fprintf(stdout,"%-15s\t%-5d\t%-10.2f\t%-5d\t%-10.2f\n",item,number,price,quantity,value);
    }
    fclose(fp);
    printf("\n");
}
--------------------------------------------

Remarks:

1. This program first asks user to give a file name in which the data was previously stored then opens the file with given file name in read mode. Note that when a file is opened in read mode, the file pointer fp gets pointer to first character of file if the file is existing otherwise NULL is assigned to fp.
2. If program tries to access location pointed by variable having value NULL, UNIX gives segmentation fault and in WINDOWS the program stops working. To avoid these situations I have checked the value of fp and if it is found NULL (means the file was not opened successfully) the program exits.
3. After passing the test of if statement the program reads the data from the file. fscanf() is the function used to do this. This function works in exact same manner as scanf() but takes an extra argument file pointer so that it can recognize the file from which the data is to be read.
4. After the data is read from the file in suitable variable, it can be used in whatever way we want.
5. The program calculates the cost of purchase by multiplying quantity and price of one item and assigns to variable named value.
6. Now all the previous data with one extra column (value) is printed on the screen.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply