【问题标题】:fprintf overwriting other data in Cfprintf 覆盖 C 中的其他数据
【发布时间】:2014-05-29 13:42:14
【问题描述】:

我正在尝试将 struct employee 写入文件,但无论我输入 case 语句多少次,它都只会写入最近输入的一个。

    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; 
     }

【问题讨论】:

    标签: c file-io printf file-management


    【解决方案1】:

    append 模式而不是write 模式打开文件。

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

    此语句以binarywrite 模式打开文件program.bin。这种模式意味着每次打开文件时,文件的初始内容都会被截断。

    你应该使用:

    fptr=fopen("program.bin","ab");append 模式打开文件。

    更多详情请访问this link

    【讨论】:

    • 我认为C standard 7.21.5.3 提供了比该链接更好的解释,因为它包含 fopen 参数的所有组合的完整列表。
    • 一开始我认为这很容易阅读和理解。
    【解决方案2】:

    您每次都在覆盖文件的内容,因为您使用模式w 来写入文件,这会从头开始重新写入文件。如果您只是想将数据附加到文件末尾,则应使用模式a,如下所示:

    fptr=fopen("program.bin","ab");
    //                        ^ Using 'append' mode, rather than 'write' mode.
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      相关资源
      最近更新 更多