我无法理解fwrite finction在c中是如何工作的。我已经制作了一个c程序。它在哪里: -
#include <stdio.h>
int main()
{
struct books
{
char name[100];
float price;
int pages;
}book1;
puts("enter the name of the book");gets(book1.name);
puts("enter the price of the book");scanf("%f",&book1.price);
puts("enter the pages of the book");scanf("%d",&book1.pages);
FILE *b=fopen("Book.txt","w");
fwrite(&book1,sizeof(book1),1,b);
}
这是程序的输入: -
$ ./a.out
enter the name of the book
Voldemort the last BSD user
enter the price of the book
40000
enter the pages of the book
34
以下是文件的内容: -
$ cat Book.txt
Voldemort the Great Linux and bsd user!����c����@�@��,B
因此我的计划出了什么问题? fwrite是如何工作的?我什么时候应该使用它?
答案 0 :(得分:0)
Nothing is immediately wrong with your program, except that you use gets()
, which is very wrong (a guaranteed buffer overflow), but has nothing to do with your question, so I just leave the hint here: Use fgets()
and for general information how to reliably get input in C, I recommend reading
As for your question, fwrite()
writes whatever you give it to a file in exactly the same way it's in the memory of your computer. You could read this same file again with fread()
and end up with the same struct
. But be aware the representations of data types are implementation defined. So you can't for example read this file on a different machine, or even on the same machine with a program compiled using a different compiler. Therefore, using fwrite()
to write whole struct
s is of very limited use in practice.
As for why you see "strange stuff" with cat
, that's simply because cat
interprets all file contents as characters. You would see the same if you would just write your float
and int
to stdout
directly, instead of formatting it with printf()
.
To write struct
s in a portable way to a file, you have to apply some sort of data serialization. A very simple way would be to use fprintf()
with a sensible format string. There are many possibilities to do that, you could e.g. use a JSON format with an appropriate JSON library, same goes for XML.
答案 1 :(得分:-3)
这是对的。 fwrite写入写入文件二进制文件,在文件中创建结构占用的内存的精确副本。如果要在文本表单中保存二进制成员/字段,则需要对其进行序列化,即将二进制数据转换为文本并将转换后的数据写入文件。
例如,代替fwrite
使用fprintf
fprintf(b, "%s,%f,%d\n", book1.name, book1.price, book1.pages);