c - 从txt文件中读取数据到链表

标签 c file linked-list

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

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

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

#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

谢谢

最佳答案

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

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

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

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

关于c - 从txt文件中读取数据到链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16359366/

相关文章:

c - 用 C 将结构写入文件

regex - 从文本文件中删除长行(Notepad++/EditPlus)

php - 一个 PHP 脚本可以让用户从我的网站下载文件而不显示我网站中的实际文件链接?

c - 链表打印不正确

c - 用 popen() 打开的文件没有 EOF?

c - 在 c 中按星期几分组列表

有人可以向他解释一下这段代码是如何工作的吗?

c - C中指向不同数据类型的指针

c - 我的双链表中的所有内容都变成 0

c - 哪个更好地存储 ANSI C 链表?通过使用 *head 或通过使用其他结构?