C:输出错误链接列表以及写入和读取文件

时间:2017-01-03 12:52:17

标签: c struct linked-list fwrite fread

我试图创建一个包含数字的链接列表并将这些数字写入文件,然后读取同一文件并读取文件中的数据并打印这些数字。

认为问题是,在阅读文件时出现了问题。

我已经添加了som打印语句用于调试,当打印我正在写入文件时,它看起来没问题。但是当我正在阅读文件并打印时,我得到第一个数字,用户输入了两次打印。 例如:

input: 1,2,3
output:3,2,1,1

我真的不知道我的链表是否有问题,写入文件或是否是阅读。所以我很感激任何有助于我更好理解的输入。

由于

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


typedef struct postTyp
{
    int num;
    struct postTyp *next;
}postTyp;

FILE *fp;

int main()
{
    postTyp *l, *p; //l=list , p=pointer

    l = NULL;
    p=malloc(sizeof(postTyp));


    //Creates linked list until user enters 0
    printf("Enter a number, 0 to exit: ");
    scanf("%i", &p->num);

    while (p->num != 0)
    {
        p->next=l;
        l=p; 
        p=malloc(sizeof(postTyp)); 
        printf("Enter a number, 0 to exit: ");
        scanf("%i", &p->num);

    }
    free(p);
    p=l;

    //write the linked list to file 
    fp = fopen("test.txt", "w");
    while(p->next != NULL)
    {
        printf("%2i", p->num);
        fwrite(p, 1, sizeof(postTyp), fp);
        p=p->next;
    }
    printf("%2i", p->num);
    fwrite(p, 1, sizeof(postTyp), fp);
    fclose(fp);

    printf("\n");

    //Code below to read the file content and print the numbers 
    fp = fopen("test.txt", "r");

    fread(p,sizeof(postTyp),1,fp);
    fseek(fp,0,SEEK_SET);

    //The first number entered at the beginning, will be printed twice here.
    while(!feof(fp))
    {
       fread(p,sizeof(postTyp),1,fp);
        printf("-----\n");
        printf("%i\n", p->num); 
    }

    fclose(fp);


    return 0;


}

1 个答案:

答案 0 :(得分:2)

来自fread手册(https://linux.die.net/man/3/fread):

fread()不区分文件结束和错误,并且调用者必须使用feof(3)和ferror(3)来确定发生了什么。

因此,您必须在打印p-&gt; num。

之前检查fread返回值