【发布时间】: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