在哪里以及如何在 c 中使用 fwrite 函数
Where and how to use fwrite function in c
我只是无法理解 fwrite 函数在 c.I 中是如何工作的 program.here 它:-
#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 是如何工作的?我应该什么时候使用它?
这是正确的。 fwrite 写入写入文件二进制文件,从而精确复制文件中结构占用的内存。如果要以文本形式保存二进制成员/字段,则需要对其进行序列化,即将二进制数据转换为文本并将转换后的数据写入文件。
例如 fwrite
使用 fprintf
fprintf(b, "%s,%f,%d\n", book1.name, book1.price, book1.pages);
你的程序没有立即出错,除了你使用 gets()
,这是 非常错误的 (保证缓冲区溢出),但与你的问题,所以我只是在这里留下提示:使用 fgets()
以及如何在 C 中可靠地获取输入的一般信息,我建议阅读
关于您的问题,fwrite()
将您提供的任何内容写入文件的方式与它在计算机内存中的方式完全相同。您可以使用 fread()
再次读取同一个文件并以相同的 struct
结束。但是请注意数据类型的表示是实现定义的。所以你不能在不同的机器上读取这个文件,甚至不能在同一台机器上用不同的编译器编译程序。因此,使用 fwrite()
来写整个 struct
s 在实践中的用处非常有限。
至于为什么你看到“奇怪的东西”和cat
,那只是因为cat
将所有文件内容解释为字符。如果您直接将 float
和 int
写入 stdout
,而不是使用 printf()
格式化 ,您会看到相同的结果.
要以可移植的方式将 struct
写入文件,您必须应用某种 数据序列化 。一种非常简单的方法是将 fprintf()
与合理的格式字符串一起使用。有很多可能性可以做到这一点,例如,您可以使用带有适当 JSON 库的 JSON 格式,XML.
也是如此
我只是无法理解 fwrite 函数在 c.I 中是如何工作的 program.here 它:-
#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 是如何工作的?我应该什么时候使用它?
这是正确的。 fwrite 写入写入文件二进制文件,从而精确复制文件中结构占用的内存。如果要以文本形式保存二进制成员/字段,则需要对其进行序列化,即将二进制数据转换为文本并将转换后的数据写入文件。
例如 fwrite
使用 fprintf
fprintf(b, "%s,%f,%d\n", book1.name, book1.price, book1.pages);
你的程序没有立即出错,除了你使用 gets()
,这是 非常错误的 (保证缓冲区溢出),但与你的问题,所以我只是在这里留下提示:使用 fgets()
以及如何在 C 中可靠地获取输入的一般信息,我建议阅读
关于您的问题,fwrite()
将您提供的任何内容写入文件的方式与它在计算机内存中的方式完全相同。您可以使用 fread()
再次读取同一个文件并以相同的 struct
结束。但是请注意数据类型的表示是实现定义的。所以你不能在不同的机器上读取这个文件,甚至不能在同一台机器上用不同的编译器编译程序。因此,使用 fwrite()
来写整个 struct
s 在实践中的用处非常有限。
至于为什么你看到“奇怪的东西”和cat
,那只是因为cat
将所有文件内容解释为字符。如果您直接将 float
和 int
写入 stdout
,而不是使用 printf()
格式化 ,您会看到相同的结果.
要以可移植的方式将 struct
写入文件,您必须应用某种 数据序列化 。一种非常简单的方法是将 fprintf()
与合理的格式字符串一起使用。有很多可能性可以做到这一点,例如,您可以使用带有适当 JSON 库的 JSON 格式,XML.