马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
fwrite 函数文档
函数概要:
fwrite 函数用于将指定尺寸的数据写入到指定的文件中。
函数原型:
#include <stdio.h>
...
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
参数解析:
参数 | 含义 | ptr | 指向存放数据的内存块指针,该内存块的尺寸最小应该是 size * nmemb 个字节 | size | 指定要写入的每个元素的尺寸,最终尺寸等于 size * nmemb | nmemb | 指定要写入的元素个数,最终尺寸等于 size * nmemb | stream | 该参数是一个 FILE 对象的指针,指定一个待写入的文件流 |
返回值:
1. 返回值是实际写入到文件中的元素个数(nmemb);
2. 如果返回值与 nmemb 参数的值不同,则有错误发生。
演示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char name[40];
char author[40];
char publisher[40];
struct Date date;
};
int main(void)
{
FILE *fp;
struct Book *book_for_write, *book_for_read;
// 为结构体分配堆内存空间
book_for_write = (struct Book *)malloc(sizeof (struct Book));
book_for_read = (struct Book *)malloc(sizeof (struct Book));
if (book_for_write == NULL || book_for_read == NULL)
{
printf("内存分配失败!\n");
exit(EXIT_SUCCESS);
}
// 填充结构体数据
strcpy(book_for_write->name, "《带你学C带你飞》");
strcpy(book_for_write->author, "小甲鱼");
strcpy(book_for_write->publisher, "清华大学出版社");
book_for_write->date.year = 2017;
book_for_write->date.month = 11;
book_for_write->date.day = 11;
if ((fp = fopen("file.txt", "w")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_SUCCESS);
}
// 将整个结构体写入文件中
fwrite(book_for_write, sizeof(struct Book), 1, fp);
// 写入完成,关闭保存文件
fclose(fp);
// 重新打开文件,检测是否成功写入数据
if ((fp = fopen("file.txt", "r")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
// 在文件中读取结构体并打印到屏幕上
fread(book_for_read, sizeof(struct Book), 1, fp);
printf("书名:%s\n", book_for_read->name);
printf("作者:%s\n", book_for_read->author);
printf("出版社:%s\n", book_for_read->publisher);
printf("出版日期:%d-%d-%d\n", book_for_read->date.year, book_for_read->date.month, book_for_read->date.day);
fclose(fp);
return 0;
}
|