如何将链接列表写入文件 [英] How to write a linked list to a file
问题描述
我是一名新程序员,在将链接列表写入文本文件时遇到了一些麻烦.这是我的代码:
I'm a new programmer and I am having some troubles writing a linked list to a text file. Here's my code:
typedef struct N {
int code;
char name[MAX1];
int items;
float price;
struct N *next;
} node_t;
typedef struct {
int code;
char name[MAX1];
int items;
float price;
} product;
product p;
product *ptr = &p;
node_t *iterator = head;
FILE *fp;
fp = fopen("newfile.txt", "w+");
while (iterator != NULL) {
p.code = iterator->code;
strcpy(p.name, iterator->name);
p.items = iterator->items;
p.price = iterator->price;
fwrite(ptr, 1, sizeof(product),fp);
iterator = iterator->next;
}
这时,我从流中读取并显示我应该写在"newfile.txt"上的内容,但是打印出来的只是'0',这里应该有一个整数/浮点数,什么都没有,应该有一个字符串.我也尝试过使用fputs()和其他函数将一个简单的整数写入文件,但它会打印出随机数.如果您想知道,由于我没有在此处复制整个代码,因此列表不是空的,因此我可以正确显示其中的所有项目.如果我不清楚,很抱歉,但这是我在这里的第一篇文章.希望有人能帮助我,谢谢!
at this point, I read from stream and display what I should have written on "newfile.txt", but all it prints out is '0' where there should be an integer/float and nothing where there should be a string. I've also tried writing to the file a simple integer with fputs() and other functions, but it printed out random numbers. In case you are wondering, since I haven't copied the whole code here, the list is NOT empty and I can display correctly all of the items in it. I'm sorry if I haven't been clear, but this is my first post here. Hope someone can help me, thank you!
推荐答案
fwrite
只是写入数据的二进制表示形式,而不是您可能希望在文本文件中看到的ASCII表示形式.例如,一个整数将由四个 NUL
字符表示,您将无法看到它们.因此,您的代码可能会正常工作.
fwrite
just writes the binary representation of the data, rather than an ASCII representation as you might expect to see in a text file. An integer, for instance, will be represented by four NUL
characters, which you won't be able to see. So your code might well be working.
如果要以 text 形式写出内容,请使用 fprintf
,例如:
If you want to write something out as text, use fprintf
, e.g.:
fprintf(fp, "%d,%d,%lf,\"%s\"\n",
iterator->code, iterator->items, iterator->price, iterator->name);
将近似为CSV(请注意,名称中不会转义字符).
would be a rough approximation of CSV (note it doesn't escape characters inside the name).
顺便说一句,为什么不仅仅添加一个 node_t
的成员变量,它是一个 product
?然后,您可以避免所有复制.
By the way, why not just make add a member variable of node_t
which is a product
? Then you can avoid all that copying about.
这篇关于如何将链接列表写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!