【问题标题】:read data from txt file to linked list从txt文件读取数据到链表
【发布时间】:2013-05-03 12:50:35
【问题描述】:

该代码用于创建商店采购、库存维护系统 我在使用 fscanf(fp,............) 函数将数据从 txt 文件输入到链表时遇到问题;

下面的代码在 cmets 部分中存在问题,但简而言之,当我在 turbo c 中运行代码并在运行时输入数据时,如果我没有读取较旧的内容,则内容会正确进入文件。每次我打开程序时,文件都会被覆盖。 当我用 fscanf() 读取内容时,垃圾值开始添加到文件中,我不知道为什么。可能是因为我使用的是指针而不是对象,但我不知道另一种方式。

我知道我的程序效率低下,但我仍然想知道代码有什么问题以及如何解决它 我使用了很多变量,其中一些可能永远不会使用,请原谅我。 代码中的问题会在create函数中找到:

#include<alloc.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<graphics.h>
#define size 20
struct shop{
char name[size];
int quantity;
int price;
struct shop *next;
}*start;
typedef struct shop sh;

char u_name[30];
char u_pass[30];

int i,user,password;
int k=0,l=0;
char add_more;
char c,choice,c1,more;




void create()
{ FILE *fc,*fp;

struct shop *ptr,*temp,*g,*l,*m,*t,*i,*d;
char ch,v[20];
int r,z,w,flag=0;
//the code ***************from here******************
fc=fopen("storedata.txt","r");
d=(sh*)malloc (sizeof(sh));
d->next=NULL  ;
i=d;
m=d;


while(fscanf(fc,"%s\t%d\t%d",m->name,m->quantity,m->price)!=EOF)
{
d=(sh*)malloc (sizeof(sh));
m->next=d;
m=m->next;

}
m->next=NULL;
fclose(fc);

t=i;

clrscr();
printf("NAME\t\t\tQUANTITY\t\t\t\tPRICE(RS)");

do
{
printf("\n%s ",t->name);
printf("\t\t\t%-20d",t->quantity);
printf("\t\t\t%-40d",t->price);
t=t->next;
}while(t!=NULL);
 getch();
 getch();
//*************till here********the smaller code part above is the code to read in the file which doesnt work correctly
start=i;}  // when i remove this line all the values entered in the file are correct but file is overridden every time i run it

谢谢

【问题讨论】:

  • 请将代码缩减为能够重现您的问题的最小测试用例,并学习如何使用调试器/将代码与 printfs 一起使用以弄清楚它在做什么。跨度>
  • 请将代码缩短为relevant parts - 并格式化。
  • @Mat 相关部分是在创建函数中读取标有 cmets 的文件。我不知道如何在此注释部分添加代码块。问题在于将文件读取到链表。很抱歉给您带来不便

标签: c file linked-list


【解决方案1】:

与 scanf 一样,fscanf 需要存储由格式参数表示的信息的位置/地址。以下用法不正确:

fscanf(fc,"%s\t%d\t%d",m->name,m->quantity,m->price);

由于m-&gt;quantitym-&gt;price 都不是有效地址,您应该使用&amp; 运算符:

fscanf(fc,"%s\t%d\t%d",m->name,&m->quantity,&m->price);

【讨论】:

  • 您提供的这段代码正在正确读取链接列表的内容,但带有一些垃圾值。早些时候,除了将字符串和各种行添加到文件中之外,所有内容都是垃圾。现在正在读取数量和价格,但正在添加 1 或 2 个带有垃圾(名称价格和数量)的垃圾块。请帮忙。也感谢上述帮助。
  • 您必须查看正在写入文件的数据,我无法再查看完整的代码。但如果我没记错的话,我在 scanf() 中发现了一个类似的错误,你正在做类似的事情:scanf("%s", &amp;m-&gt;name);,这也是错误的。
【解决方案2】:

fscanf() 的返回值处理已关闭。

它不返回指针,而是返回intsee the documentation。整数是成功转换的次数;您应该将该值与格式字符串中的 % 说明符的编号相匹配。

它需要指向数据存储位置的指针;像%d 这样的整数转换需要int 的地址,即代码中的&amp;m-&gt;quantity

在C中也是don't cast the return value of malloc()。其实重写

d=(sh*)malloc (sizeof(sh));

作为:

d = malloc(sizeof *d);

为了更清晰、更少重复和更简洁。

【讨论】: