facebook like button

04 June, 2011

program 54: writing to a file in C

The need:
 In previous post I talked of file handling. Reading and writing both are important operations on a file. This program will take some content from user and store that in a file. So this program is only a rehearsal of writing 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 want to save your data. => ");
    gets(filename);
    fp=fopen(filename,"w");   //opening file
    printf("Input file data.\n");
    for(i=0;i<ITEMS;i++)
    {
        printf("Item_name =>\t");
        scanf("%s",item);
        printf("number =>\t");
        scanf("%d",&number);
        printf("price =>\t");
        scanf("%f",&price);
        printf("quantity =>\t");
        scanf("%d",&quantity);
        fflush(stdin);
        fprintf(fp,"%s %d %f %d\n",item,number,price,quantity);
    }
    fprintf(stdout,"\nAll data has been entered in file %s\n",filename);
    fclose(fp);
}
--------------------------------------------

Remarks:

1. This program first opens a file with given file name in write mode. Note that when a file is opened in write mode, the previous file with same name is overwritten is existed otherwise a new file is created.
2. ITEM is defined as 1 so the program takes data for only one item.
3. Data about the item is taken from the user by 4 scan operations.
4. After that the data is written on the file. fprintf() is the function used to do this. This function works in exact same manner as printf() but takes an extra argument file pointer so that it can recognize the file in which the data is to be written.
5. The second last statement is a replacement simple printf() statement (recall stdout is default file pointer to output window).
6. Last statement closes the file.
7. After the program terminates we can see the output file in the same folder in which the program was build and run. We can see the contents of file by opening it with notepad (in windows) or gedit (in unix based OS).

3 comments:

  1. what is the use of fflush(stdin)?

    ReplyDelete
  2. fflush(stdin) is used to flush out previous undesired inputs of keyboard.

    ReplyDelete
  3. you can refer to posts ( links ) given below for details of fflush():
    http://programsimply.blogspot.com/2011/04/program-25-characters-and-strings.html
    http://programsimply.blogspot.com/2011/05/program-39-equilateral-star-triangle.html

    ReplyDelete

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