Pages

Wednesday, December 8, 2010

Writing a file in binary mode

To write a binary file the function that we will use is "fwrite()".  The "fwrite()" function can write binary data to a file.

Syntax
    fwrite(&data,sizeof_data,no_of_rec,filepointer)
   
Here, the first argument is the address of the structure or variable which we want to write to the file. The second argument is the size of the structure in bytes. We can calculate the size manually(int 2 byes, float etc), but this approach is not recommended since the size of data type depends on the processor.  Therefore instead of calculating it ourselves, we use the "sizeof()" operator to do the same. The sizeof( ) operator gives the size of the variable in bytes. This will help us in 2 ways - first, we won't have to perform  the calculations manually, and secondly if the datatype of the data to be written is changed, we don't need to make changes in the program.The third argument is the number of such structures that we want to write at one time. In this case, we want to write only one structure at a time. Had we had an array of structures, for example, we might have wanted to write the entire array at once.The last argument is the pointer to the file we want to write to.


Example 1 : Writing a record to a file

#include
#include
struct person
{
    char name[12];
    int age;
};
void main()
{
    clrscr();
    FILE *fp;
    fp=fopen("list","w");
    person p;
    printf("\nEnter name ");
    scanf("%s",&p.name);
    printf("\nEnter age ");
    scanf("%d",&p.age);
    fwrite(&p,sizeof(person),1,fp);
    printf("\n1 person added");
    fclose(fp);
}

Description

The above program is a basic example of how the data of a structure(record) can be saved to a file. The program starts with a structure declaration with two member variables, name and age. In main, we have created an object of the structure "person" with the name "p". If you remember, we can not access the structure variables directly. We must create an object to access all the members using the "objectname.membername" notation, for example "p.name". When all the values have been entered by the user, we will not write "name" and "age" in the file separtely since both of them are inside the object "p". If we can somehow write the value of "p" in the file both "name" and "age" will be saved.
To save the data in binary format the function "fwrite()" has been used. "fwrite()" has been given 4 arguments.
  • First argument (&p) : is the address of the object that has to be saved in the file. It will contain all the values that were present in the structure.
  • Second argument (sizeof(person)) : is the size of memory that will be required to save this data. The "sizeof" operator will automatically calculate the memory occupied by the structure.
  •     Third argument (1) : is the number of structures that we want to write. Since we want to write only one structure at time 1 is written.
  •     Fourth argument (fp) : is the file pointer in which we want to store the data.


After running this program, try to read the file "list" using any method. You will see that the data printed will not be readable. Why is it so? because the file has been written the using the binary function "fwrite()". The data has been written in binary format which can not be read directly. We will learn about reading such files later.

Example 2 : Writing multiple records to a file

#include
#include
struct books
{
    int bookno,price;
    char name[12],pub[20];
};
void main()
{
    clrscr();
    char c;
    FILE *fp;
    fp=fopen("library.dat","a");
    books b;
    do
    {
    printf("\nBook no ");
    scanf("%d",&b.bookno);
    fflush(stdin);
    printf("\nEnter book name ");
    gets(b.name);
    printf("\nEnter publisher ");
    gets(b.pub);
    printf("\nEnter book price ");
    scanf("%d",&b.price);
    fwrite(&b,sizeof(books),1,fp);
    fflush(stdin);
    printf("\nNew book added to library.");
    printf("\nPress Y to add more books, N to Close : ");
    scanf("%c",&c);
    }while(c=='Y' || c=='y');
    fclose(fp);
}


Description
    Logically, this program is similar to the previous "person" program. The only new thing we have done here is that we have written the "fwrite()" function inside the loop. This will allow the user to enter as many records as needed.


Till now what we have written to the files is entered by ther user himself. Sometimes, there can be a condition that we want to accept some data from the user and some values are to be calculated.Let's make a program to do so.
Example 3 - Writing calculated values to the file

#include
#include
struct student
{
    int rollno,marks1,marks2,marks3,total,avg;
    char name[10];
};
void main()
{
    student s;
    FILE *fptr;
    fptr=fopen("school","a");
    char ch;
    for(int i=0;i<5;i++)
    {
        printf("\nRollno ");
        scanf("%s",&s.rollno);
        printf("\nName ");
        scanf("%s",&s.name);
        printf("\nMarks 1 ");
        scanf("%d",&s.marks1);
        printf("\nMarks 2 ");
        scanf("%d",&s.marks2);
        printf("\nMarks 3 ");
        scanf("%d",&s.marks3);
        s.total=s.marks1+s.marks2+s.marks3;
        s.avg=s.total/3;
        fwrite(&s,sizeof(student),1,fptr);
        printf("\nSaved in the file");
    }
    fclose(fptr);
}


Description
In this program we are writing the data of 5 students using a for loop. A student record has 7 values rollno,name,marks1,marks2,marks3,total and average. Out of these 7 values, 5 are being entered by the user and 2 are being calculated by the program. Total is calculated by adding all three marks, whereas avg has been achieved by dividing the total by 3. When we write the data using "fwrite()", we are writing the value of "s" which has 7 values in total, 5 entered by the user and 2 calculated values. In this way we can store customized values to the file.

0 comments:

Post a Comment