c - Fwrite 无法正常工作

标签 c

很抱歉这个程序是用我的母语编写的,但我似乎真的找不到它不起作用的原因。因此,我进行了测试,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/

相关文章:

c - 为 ext2 文件系统添加挂载选项

c++ - 为将来的 QThreadPool 线程和/或 pthread_create 调用设置默认堆栈大小

c - 尝试使用 scanf 读取数字时程序崩溃

c - 哪种排序算法对 c 中具有唯一元素的结构数组快速

c - 使用 C 中的子进程发送和处理信号时遇到问题

c - GetTempPathA 我怎么会提前知道大小?

c - 不断收到堆栈粉碎错误

c - 有没有像 npm 或 apt-get 这样的 cpm?

linux - 在Linux单板计算机上安装USB以在C程序中使用

c - 遍历 const 矩阵和 vector