C:输出错误链表和写入和读取文件
C: Output error linked-lists and writing to and reading from file
我正在尝试创建一个包含数字的链表并将这些数字写入文件,然后读取同一个文件并读取文件中的数据并打印这些数字。
我认为问题是,读取文件时出现问题。
我添加了一些用于调试的打印语句,当打印我正在写入文件的内容时,它看起来没问题。但是当我读取文件并打印时,我得到了用户输入的第一个数字打印了两次。
例如:
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;
}
来自 fread 手册 (https://linux.die.net/man/3/fread):
fread() 不区分文件结束和错误,调用者必须使用 feof(3) 和 ferror(3) 来确定发生了什么。
因此,您必须在打印 p->num.
之前检查 fread return 值
我正在尝试创建一个包含数字的链表并将这些数字写入文件,然后读取同一个文件并读取文件中的数据并打印这些数字。
我认为问题是,读取文件时出现问题。
我添加了一些用于调试的打印语句,当打印我正在写入文件的内容时,它看起来没问题。但是当我读取文件并打印时,我得到了用户输入的第一个数字打印了两次。 例如:
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;
}
来自 fread 手册 (https://linux.die.net/man/3/fread):
fread() 不区分文件结束和错误,调用者必须使用 feof(3) 和 ferror(3) 来确定发生了什么。
因此,您必须在打印 p->num.
之前检查 fread return 值