【发布时间】:2018-08-13 07:55:28
【问题描述】:
我正在尝试一个 C 语言程序,但遇到了一些困难。
问题:我在我的项目中使用文件,但是当我倒带我的 file1 时,它会在 file2 中复制相同的数据。我该如何解决这个问题?
您可以参考下面的代码。
void calculate_bill ()
{
system("cls");
int quan,q;
printf("Enter the number of item : ");
scanf("%d",&quan);
char sell[100];
float total=0,gtotal=0;
file1=fopen("object.txt","r");
file2=fopen("temp.txt","w");
//printf("SN\tITEM NAME\tCODE\tRATE\t\tQUANTITY\tTOTAL\n");
rewind(file1);
for(int i=1;i<=quan;i++)
{
rewind(file1);
printf("Enter the item name : ");
scanf("%s",&sell);
printf("Enter the item quantity : ");
scanf("%d",&q);
while(fscanf(file1,"%s %d %f %d",&object.name,&object.code,&object.rate,&object.quantity)!=EOF)
{
if(strcmp(sell,object.name)==0)
{
total=object.rate*q;
gtotal=gtotal+total;
object.quantity=object.quantity-q;
fprintf(file2,"%s\t\t%d\t%f\t%d\n",object.name,object.code,object.rate,object.quantity);
}
else
fprintf(file2,"%s\t\t%d\t%f\t%d\n",object.name,object.code,object.rate,object.quantity);
}
}
fclose(file1);
fclose(file2);
remove("object.txt");
rename("temp.txt","object.txt");
printf("The total amount is : %.2f",gtotal);
getch();
system("cls");
d_mainmenu();
}
输出:
SN ITEM NAME CODE RATE QUANTITY
1 abed 105 100.000000 7
2 maruf 100 100.000000 9
3 adi 106 100.000000 10
4 anik 89 1.000000 1
5 abed 105 100.000000 8
6 maruf 100 100.000000 9
7 adi 106 100.000000 9
8 anik 89 1.000000 1
9 abed 105 100.000000 8
10 maruf 100 100.000000 9
11 adi 106 100.000000 10
12 anik 89 1.000000 0
我需要这样的输出...
SN ITEM NAME CODE RATE QUANTITY
1 abed 105 100.000000 7
2 maruf 100 100.000000 9
3 adi 106 100.000000 10
4 anik 89 1.000000 1
使用此功能后。
【问题讨论】:
-
每次输入内容时,都会将所有条目附加到输出中。我认为您最好先将所有数据读入合适的结构,然后修改数据,然后在完成后写入更新的数据。
-
先生,您能给我一个示例代码吗?
-
您的期望是什么?你想减少 object.file 中的对象数量吗?