问题
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;
}
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!
回答1:
I would suggest the following changes:
Divide the
struct
for each node into twostruct
s - one for holding the data and one for capturing the next pointer.typedef struct { int code; char name[MAX1]; int items; float price; } NodeData; typedef struct N { NodeData data; struct N *next; } node_t;
Now the function to write the contents of a linked list can be:
fp = fopen("newfile.txt", "w+"); // Get the size of the linked list and write as the first piece of data. size_t listSize = getLinkedListSize(head) fwrite(&listSize, 1, sizeof(size_t), fp); // Now write each node of the linked list. while (iterator != NULL) { fwrite(&(iterator->data), 1, sizeof(iterator->data), fp); iterator = iterator->next; }
回答2:
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.
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);
would be a rough approximation of CSV (note it doesn't escape characters inside the name).
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.
来源:https://stackoverflow.com/questions/28033922/how-to-write-a-linked-list-to-a-file