对fread的分割错误

时间:2017-04-30 07:27:33

标签: c segmentation-fault binaryfiles fread

当我尝试使用fread时,我一直遇到分段错误。该文件存在且不为空。

NodePtr lnodePtr = NULL;
NodePtr fnodePtr = NULL;
NodePtr idnodePtr = NULL;
NodePtr gnodePtr = NULL;

printf("1b\n");
FILE *studentData = malloc(sizeof(FILE));
printf("2b\n");
int numRecords = 0;
printf("3b\n");
SREC student;

printf("4b\n");
if (fopen("database", "rb") != NULL)
{
    printf("5b\n");
    while (fread (&student, sizeof(SREC), 1, studentData) == 1)//happens here
    {
        printf("6b\n");
        insert (&lnodePtr, student, 1);
        insert (&fnodePtr, student, 2);
        insert (&idnodePtr, student, 3);
        insert (&gnodePtr, student, 4);
        printf("7b\n");
        numRecords++;
    }
}
printf("8b\n");

我也尝试将其更改为此并仍然给我一个分段错误

NodePtr lnodePtr = NULL;
NodePtr fnodePtr = NULL;
NodePtr idnodePtr = NULL;
NodePtr gnodePtr = NULL;

printf("1b\n");
FILE *studentData = malloc(sizeof(FILE));
printf("2b\n");
int numRecords = 0;
printf("3b\n");
SREC *student = malloc(sizeof(SREC));

printf("4b\n");
if (fopen("database", "rb") != NULL)
{
    printf("5b\n");
    while (fread (student, sizeof(SREC), 1, studentData) == 1)//happens here
    {
        printf("6b\n");
        insert (&lnodePtr, *student, 1);
        insert (&fnodePtr, *student, 2);
        insert (&idnodePtr, *student, 3);
        insert (&gnodePtr, *student, 4);
        printf("7b\n");
        numRecords++;
    }
}
printf("8b\n");

这是我正在使用的结构:

typedef struct student {
    char lname[ 10 ], initial, fname[ 10 ];
    unsigned long SID;
    float GPA;
} SREC;

typedef struct node {
    SREC s;
    struct node *nextPtr;
} Node;

typedef Node *NodePtr;

我也正确地从二进制文件中读取?我正在尝试阅读一堆SREC,并将它们添加到链接列表中,我是读取和写入C中二进制文件的新手。

编辑:这是我写入文件idk的方式,如果这会弄乱任何东西:

        printf("begin\n");
        studentData = fopen("database", "wb");
        while(lnodePtr != NULL)
        {
            fwrite(&(lnodePtr->s), sizeof(SREC), 1, studentData);
            lnodePtr = lnodePtr->nextPtr;
        }
        printf("end\n");

Edit2:已解决!谢谢你们

0 个答案:

没有答案