Question

I am trying to write the struct employee to file, but it will only write the most recent entered one, no matter how many times I enter the case statement.

    case '1':
    {
        fptr=fopen("program.bin","wb");

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

        printf("\nA is: %d\n",a);

        printf("\nPlease enter the employee's ID: ");
        scanf("%s",&employee[a].ID);
        fprintf(fptr,"Employees ID number:     %s\r\n",employee[a].ID);

        printf("\nPlease enter the employee's first name: ");
        scanf("%s",&employee[a].firstname);
        fprintf(fptr,"Employees first name:    %s\r\n",employee[a].firstname);

        printf("\nPlease enter the employee's Surname: ");
        scanf("%s",&employee[a].surname);
        fprintf(fptr,"Employees surname:       %s\r\n",employee[a].surname);

        printf("\nPlease enter the employee's Home address: ");
        scanf("%s",&employee[a].address);
        fprintf(fptr,"Employees address is:    %s\r\n",employee[a].address);

        printf("\nPlease enter the employee's department number: ");
        scanf("%s",&employee[a].department);
        fprintf(fptr,"Employees department is: %s\r\n",employee[a].department);

        printf("\nPlease enter the employee's duration: ");
        scanf("%s",&employee[a].duration);
        fprintf(fptr,"Employees duration is:   %s\r\n",employee[a].duration);

        a++;

        fclose(fptr);

        goto CASE; 
     }
Was it helpful?

Solution

Open the file in append mode not in write mode.

fptr=fopen("program.bin","wb");

this statement opens the file program.bin in binary write mode. This mode means everytime the file is opened, the initial contents of file will be truncated.

You should use:

fptr=fopen("program.bin","ab"); to open file in append mode.

For more details visit this link

OTHER TIPS

You're overwriting the content of the file every time because you're using mode w to write the file, which re-writes the file from the beginning. If you simply want to append your data to the end of the file, you should use mode a like this:

fptr=fopen("program.bin","ab");
//                        ^ Using 'append' mode, rather than 'write' mode.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top