如何将链表写入文件 [英] How to write a linked list to a file

查看:195
本文介绍了如何将链表写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新程序员,在将链接列表写入文本文件时遇到了一些麻烦.这是我的代码:

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"
",
        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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆