【问题标题】:modify record in a file using c program使用c程序修改文件中的记录
【发布时间】:2015-11-17 18:12:56
【问题描述】:

我编写了这个 c 程序来插入、查看、修改和删除文件中的记录。文件名为 emp.dat。显示、添加和删除的代码工作正常,但修改部分不起作用。该程序要求输入详细信息以进行修改,但没有任何内容得到更新/修改。 守则:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
void main()
{
    FILE *outp,*inpt;
    char another,choice;
    struct emp
    {
        int emp_no,age;
        char name[40];
        float bs;
    };
    struct emp e;
    char empname[40];
    long int recsize;
    outp=fopen("emp.dat","r+");
    if(outp=='\0')
    {
        outp=fopen("emp.dat","w+");
        if(outp=='\0')
        {
            puts("cannot open file\n");
            exit(1);
        }
    }
    recsize=sizeof(e);
    while(1)
    {
        printf("1.Add records\n");
        printf("2.List records\n");
        printf("3.Modify records\n");
        printf("4.Delete records\n");
        printf("0. exit\n");
        printf("Your choice\n");
        fflush(stdin);
        choice=getche();
        switch(choice)
        {
            case '1':                           //code to add data
            .

            case '2':                        //code to display data

            case '3':                       //code to modify data
            another='Y';
            while(another=='Y')
            {
                printf("\nEnter name of employee to modify");
                scanf("%s",empname);
                rewind(outp);
                while(fread(&e,recsize,1,outp)==1)
                {
                    if(strcmp(e.name,empname)==0)
                    {
                        printf("\nenter new name,age & gs");
                        scanf("%d %s %d %f",&e.emp_no,&e.name,&e.age,&e.bs);
                        fseek(outp,-recsize,SEEK_CUR);
                        fwrite(&e,recsize,1,outp);
                        break;
                    }
                }
                printf("\nModify another record(Y/N)");
                fflush(stdin);
                another=getche();
            }
                        printf("\n\n");
            break;
            case '4':                         //code to delete data

            case '0':
            fclose(outp);
            printf("\n\n");
            exit(1);
        }
    }
}

从输出中可以看出,名称不会从 Zaid 变为 Cow,年龄和 gs 也是如此

【问题讨论】:

  • 你已经发布了相当多的代码。如果您创建一个最小、完整和可验证的示例,您可以增加有人阅读它并尝试帮助您的可能性。在这里阅读更多:stackoverflow.com/help/mcve
  • 这个if(outp=='\0') 应该会抛出警告,甚至是错误。就这样做if(!outp)

标签: c file-handling


【解决方案1】:

你真的应该测试返回值。

提示要求输入name,age &amp; gs,您按照要求输入它们。然而,scanf 被指示首先获取一个整数 (emp_no) ("%d %s %d %f")。错过它立即失败并且没有任何更新。

情况很容易检测到:scanf 返回成功转换的次数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多