【问题标题】:write input from user in binary file将用户的输入写入二进制文件
【发布时间】:2021-08-17 16:59:34
【问题描述】:

我正在尝试从用户那里获取输入并将其写入二进制文件。这是我的代码,它运行平稳,但是当我尝试在另一个程序中读取文件时,文件不会打开(显示为 NULL),所以我不确定为什么数据没有保存到文件中。

这是我的代码:

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

int length=2, width=2;

struct LandData
{
    int height;
};

struct LandData* WritingData()
{
    FILE *fptr;
    struct LandData *arr = (struct LandData*)malloc(length* width* sizeof(struct LandData));

    if ((fptr = fopen("data.bin","wb")) == NULL){
       printf("Error! opening file");
        exit(1);
    }

    for (int i = 0; i < length ; i++){
        for (int j = 0; j < width; j++){
            printf("choose height: ");
            scanf("%d", &(arr + i*width + j)->height);
            fwrite(arr, sizeof(struct LandData), 1, fptr);
        }
    }

    fclose(fptr);
    return(arr);
}

int main()
{
    struct LandData *arr =WritingData();
    free(arr);
    return 0;
}

这是阅读部分的代码:

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

int length =2 , width =2;

struct LandData
{
    int height;
};

int main()
{
    FILE *fptr;
    struct LandData *arr = (struct LandData*)malloc(length* width* sizeof(struct LandData));

   if ((fptr = fopen("data.bin","rb")) == NULL){
       printf("Error! opening file");
       exit(1);
   }

    while(fread(arr,sizeof(struct LandData),1,fptr))
    {
        for (int i = 0; i < length ; i++) {
            printf(" %d| ", i);
            for (int j = 0; j < width; j++)
            printf(" %d ", (arr + i*width + j)->height);
            printf("\n");
        }

        if(fclose(fptr)!=0)
        {
        perror("Error on file closing after reading");
        exit(2);
        }
    }

    free(arr);
    return 0;
}

【问题讨论】:

  • "该文件无法打开的另一个程序"。请出示该代码。
  • fwrite(arr, sizeof(struct LandData), 1, fptr); 只写出数组的一个条目,它始终是第一个条目。
  • 如果您想像“文本”编辑器一样在程序中读取文件,请将数据保存为文本。例如使用fprintf.
  • fopen 未能获得更具体的错误消息时,呼叫perror
  • @kaylum 如何让它写多个条目?

标签: c data-structures struct binaryfiles fwrite


【解决方案1】:
while(fread(arr,sizeof(struct LandData),1,fptr)) 

替换为

while(fread(arr,sizeof(struct LandData),1,fptr) != EOF)

注意EOF不是0,或者false或者NULL,它是一个值 你可以通过做这样的事情来试试这个

if(EOF){
   printf("something")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多