0

我很难理解为什么我的代码没有按预期工作,我确信这与我对 fread 和 fwrite 的理解有关。

这是我的代码片段,请原谅格式和懒惰的风格。

typedef struct record_t{
char name[20];
unsigned int id;
char toy[30];
}record_t;



int main(int argc, char** argv){


FILE *readFile, *writeFile;
record_t *recordPtr; 
int i;

if( (recordPtr = malloc(sizeof(struct record_t))) == NULL)
{
    perror("Error allocating record space\n");
    exit(EXIT_FAILURE);
}

strcpy(recordPtr->name, "Michael"); 
recordPtr->id = 3;
strcpy(recordPtr->toy, "Hello Kitty");
printf("Writing %s - %d - %d - %d - %s\n", recordPtr->name,
    recordPtr->id, recordPtr->toy);

if( (writeFile = fopen("test.bin", "wb")) == NULL)
{
    perror("Error opening writing file\n");
    exit(EXIT_FAILURE);
}

for(i = 0; i < 2; ++i){
recordPtr->id = i ;
fwrite(&recordPtr, sizeof(struct record_t), 1, writeFile);
printf("%s - %d - %s, ", recordPtr->name, recordPtr->id, recordPtr->toy);
printf("Record Written.\n");

}
fclose(writeFile);

recordPtr = NULL;

if( (readFile = fopen("test.bin", "rb")) == NULL)
{
    perror("Error opening reading file\n");
}
    exit(EXIT_FAILURE);

recordPtr = NULL;


for(i=0; i < 2; ++i){
    fread(&recordPtr, sizeof(struct record_t), 1, readFile);
    printf("%s - %d - %s, Read back.\n" recordPtr->name, recordPtr->id, recordPtr->toy);
}
fclose(readFile);


exit(EXIT_SUCCESS);
}

代码的想法只是获取一条记录,将其写入二进制文件,然后从二进制文件中读取。我的问题是只有最后一个条目被读回,所以我确定我对 fread 的理解有问题。

先感谢您。

4

2 回答 2

1

这个

fwrite(&recordPtr, sizeof(struct record_t), 1, writeFile);

不是将结构写入文件,而是尝试将指向recordPtr它的指针写入内存中跟随它的任何内容。

同样这个

fread(&recordPtr, sizeof(struct record_t), 1, readFile);

不是将结构读取到您为其分配的内存中,而是试图recordPtr用文件数据覆盖指针以及内存中跟随它的任何内容。

您需要删除该&符号。

于 2013-04-14T02:47:44.957 回答
1
fwrite(&recordPtr, sizeof(struct record_t), 1, writeFile);
fread(&recordPtr, sizeof(struct record_t), 1, readFile);

should be:

fwrite(recordPtr, sizeof(struct record_t), 1, writeFile);
fread(recordPtr, sizeof(struct record_t), 1, readFile);

Next:

if( (readFile = fopen("test.bin", "rb")) == NULL)
{
    perror("Error opening reading file\n");
}
exit(EXIT_FAILURE);

Should be

if( (readFile = fopen("test.bin", "rb")) == NULL)
{
    perror("Error opening reading file\n");
    exit(EXIT_FAILURE);
}

And

when you are reading the structure back, the buffer is pointing to NULL!!! So make sure you allocate memory and make recordPtr point to it before you use recordPtr in fread.

于 2013-04-14T03:01:44.030 回答