【发布时间】:2017-08-04 10:32:36
【问题描述】:
我只是无法理解 fwrite 函数在 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 是如何工作的?我应该什么时候使用它?
【问题讨论】:
-
你的程序有什么问题取决于你最初期望的输出。
-
你需要声明变量类型book1,你也忘了关闭文件
-
嗯,����c����@�@��,B 部分(16 字节)实际上是您的价格(8 字节)和页面数据(8 字节)。在开始将内容保存到文件之前,您首先需要了解 C/C++ 如何管理数据
-
使用
fprintf而不是fwrite如果你想以文本形式写入文件。 -
使用
fwrite/fread时,最好以binary方式打开文件。