无法将二进制文件中的数据读入结构指针数组

时间:2016-06-28 09:11:20

标签: c arrays file structure dynamic-memory-allocation

以下代码将二进制数据写入/读取二进制文件。写作成功,即使按fread返回值读取也是成功的。但最后两三个值总是垃圾,我通过增加数组大小来验证这一点。

如果我们在写完后立即读取文件,那么数值就会很好。但是如果我们在写入之后关闭程序一次,然后在第一次操作时再次运行程序,那么它会将最后几个值打印为垃圾。为什么这样?

#include<stdio.h>
#include<stdlib.h>
#define MAX 7

void write(FILE *);
void read(FILE *);

int flag=0;

struct emp
{
char name[20];
int id;
float salary;
}*e[MAX];

void write(FILE *f)
{
int i=0,check=0;

flag=1;
for(i=0;i<MAX;i++)
{
    e[i]=malloc(sizeof(struct emp));
    if(e[i])
    {
        printf("\nEnter Name id salary\n");
        scanf("%s %d %f",e[i]->name,&e[i]->id,&e[i]->salary);
        //printf("\n----------%s %d %f\n",e[i]->name,e[i]->id,e[i]->salary);
        //fflush(stdin);
    }
    else
    {
        printf("\nError allocating Memory\n");
        exit(0);
    }
}
check= fwrite(*e,sizeof(struct emp),MAX,f);
if(check!=MAX)
{
    printf("\nerror writing to file\n");
}
else
  {
    printf("\nwritten successfully to file\n");
  }
}

void read(FILE *f)
{
int i=0;

if(flag==0) //reading file right after running program
{
    for(i=0;i<MAX;i++)
    {
        e[i]=malloc(sizeof(struct emp));
        if(e[i]==NULL)
        {
            printf("\nError Allocating Memory for read\n");
            exit(0);
        }
    }
}

if(fread(*e,sizeof(struct emp),MAX,f)==MAX)
{
    for(i=0;i<MAX;i++)
    {
        printf("\n%s %d %f\n",e[i]->name,e[i]->id,e[i]->salary);
    }
}
else
{
    printf("\nEither reading error or partial content read\n");
}
}

int main()
{
FILE *fp=NULL;
char a='a';

do
{
    printf("\nEnter w to write, r to read and e to exit\n");
    //scanf("%c",&a);
    a=getche();

    switch(a)
    {
        case 'w':
                fp=fopen("binary_ptr.exe","wb");
                if(fp==NULL)
                {
                    printf("\nError opening file to write\n");
                    exit(0);
                }
                write(fp);
                fclose(fp);
                break;
        case 'r':
                fp=fopen("binary_ptr.exe","rb");
                if(fp==NULL)
                {
                    printf("\nError opening file to read\n");
                    exit(0);
                }
                read(fp);
                fclose(fp);
                break;
        case 'e':
                exit(0);
                break;
        default:
                printf("\nInvalid input\n");
                break;
    }
}
while(1);

return 0;
}

3 个答案:

答案 0 :(得分:2)

在读/写时,如图所示,假设所有结构都放在以*e开头的连续内存区域中。不是这种情况。

代码没有定义struct的数组,而是指向后者的指针。动态分配的struct本身分散在整个内存中。

目前代码调用所有MAX&gt;的未定义行为。 1写作/阅读超出*e[0]的界限。

要围绕fread() / fwrite() MAX次修复此循环,每个struct

(例如,要指出此问题使用Valgrind内存检查器显式运行已编译的代码。)

与您的问题无关的旁注:read()write()是一个拥有函数的错误名称,因为它们已被POSIX C标准使用。

答案 1 :(得分:0)

在阅读功能中,您有

if(fread(*e,sizeof(struct emp),MAX,f)==MAX)

这将MAX元素读入数组e。但是,e不是连续的数组。您分别使用

分配e
e[i]=malloc(sizeof(struct emp));

答案 2 :(得分:0)

你不能(fread(*e, sizeof(struct emp), MAX, f),因为你已经为你的构造分配了非连续的内存,正确地说,你有一个指向emp结构的指针数组,而不是一组emp结构。您需要单独阅读每个emp

for (int i = 0; i < MAX; ++i){
    if (fread(e[i], sizeof(struct emp), 1, f) == sizeof(struct emp)){
        printf("\n%s %d %f\n", e[i]->name, e[i]->id, e[i]->salary);
    } else {
        ...
    }
}

同样,当您将emp数据写入文件时,您也需要单独执行此操作

for (int i = 0; i < MAX; ++i){
    check = fwrite(e[i], sizeof(struct emp), 1, f);
    if (check != sizeof(struct emp)){
        ...
    } else {
    ...
    }
}