【问题标题】:What is wrong with the code? It is not getting out of the loop代码有什么问题?它没有脱离循环
【发布时间】:2020-06-19 20:16:35
【问题描述】:

问题场景:有2个文件customer.dattransaction.dat包含记录数(记录结构在代码定义的bt结构中)。在transacton.dat文件中有2个tran_types(d / c借方或贷方)为每次借记卡和贷记卡都会更新 customer.dat 文件中的余额。

#include<stdio.h>
main()
{
    struct tran
    {
        int accno;
        char tran_type;
        float amount;
    };
    struct tran t;
    struct cust
    {
        int accno;
        char name[30];
        float balance;
    };
    struct cust c;
    FILE *fp,*ft;
    fp=fopen("customer.dat","rb+");
    if(fp == NULL)
    {
        printf("Cant open file\n");
        exit(1);
    }
    
    ft=fopen("transaction.dat","rb");
    if(ft == NULL)
    {
        printf("Error\n");
    }
    while(fread(&c,sizeof(c),1,fp)==1)
    {
        
        rewind(ft);
        while(fread(&t,sizeof(t),1,ft)==1)
        {
            if(c.accno == t.accno)
            {
                if(t.tran_type=='d')
                {
                    c.balance=(c.balance-t.amount);
                    fseek(fp,-sizeof(c),SEEK_CUR);
                    fwrite(&c,sizeof(c),1,fp);
                    
                    
                }
                else if(t.tran_type =='c')
                {
                    
                    c.balance= (c.balance + t.amount);
                    fseek(fp,-sizeof(c),SEEK_CUR);
                    fwrite(&c,sizeof(c),1,fp);
                
                }
            }
            
        }
        
        
    }
    fclose(fp);
    fclose(ft);
    printf("Success");
}

【问题讨论】:

  • 你认为 rewind(ft) 函数调用有什么作用?
  • 外循环的每次迭代都在内循环使用的文件上调用rewind。同时,内循环可以调用fseek,在外循环使用的文件上向后移动查找位置。如果这永远循环下去也就不足为奇了。

标签: c file-io


【解决方案1】:

您的代码本质上没有任何问题。但是有两个问题:

  1. 您正在使用 printf(),但在末尾没有换行符 \n 格式字符串。这样,流不会刷新到标准输出和 将需要多次打印才能输出,或者仅当程序 结束了。

  2. 您已使用 5 秒 sleep()。根据数量 客户和交易,您的循环可能会持续很长时间。

这两个事实一起表明您可能没有等待足够的时间来接收结果。只需删除sleep(),它就会变得快速并正常工作。

【讨论】:

  • 对不起,我在发布之前忘记编辑代码了。我使用睡眠功能来停止屏幕并知道实际发生了什么(作为调试目的)。我现在已经编辑了代码
  • 我已经在这里运行了原始代码,没有调用 sleep() 并且没有任何问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
相关资源
最近更新 更多