gpt4 book ai didi

c - Fwrite 无法正常工作

转载 作者:行者123 更新时间:2023-11-30 19:40:44 25 4
gpt4 key购买 nike

很抱歉这个程序是用我的母语编写的,但我似乎真的找不到它不起作用的原因。因此,我进行了测试,a 数组的值都被正确读取,但是当我尝试查看 .dat 文件时,只有 for 函数中读取的第一个单词( a[0].marca )。

这里是输入I also tested to see if it reads correct

这是 .dat 文件 It only writes the first

#include <stdio.h>
#include <stdlib.h>

struct data
{
int anul;
int luna;
};
typedef struct data DATA;
struct automobil
{
char marca[20];
char carburant;
char model[5];
DATA fabricatie;
};
typedef struct automobil AUTOMOBIL;




int main()
{
AUTOMOBIL a[100];
int n;
FILE *f;

int i;
if((f=fopen("evidenta.dat","wb"))==NULL)
{
exit(1);
}
printf("Cate automobile sunt ?"); scanf("%d",&n); // The number of cars registered
for(i=0;i<n;i++) // getting the details about every car
{
printf("\nMarca ? : "); fflush(stdin); gets(a[i].marca);
printf("\nCarburant ? : "); fflush(stdin); getch(a[i].carburant);
printf("\nModelul? :"); fflush(stdin); gets(a[i].model);
printf("\nLuna fabricatie ? :"); scanf("%d",&a[i].fabricatie.luna);
printf("\nAn fabricatie ? : "); scanf("%d",&a[i].fabricatie.anul);

// After getting a line it has to write it in the binary file
fwrite(&(a[i]),sizeof(AUTOMOBIL),1,f); //It writes only a[0].marca
}
for(i=0;i<n;i++)
{
printf("\n %s",a[i].marca);
printf("\n %c",a[i].carburant);
printf("\n %s",a[i].model);
printf("\n %d",a[i].fabricatie.luna);
printf("\n %d",a[i].fabricatie.anul);
}

return 0;

}

最佳答案

你必须这样做:

fwrite(&(a[i]),sizeof(AUTOMOBIL),1,f);

或者,您可以在循环之外执行此操作:

fwrite(a,sizeof(AUTOMOBIL),n,f);

另外不要忘记关闭。

关于c - Fwrite 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35044227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com