捐助郴维网
感谢您对郴维网的支持,你的支持将是郴维网持续发展的动力!
二维码
×
当前位置:郴维网 >函数快查 > 正文
7 2018.02

fwrite -- 将数据写入到文件中

点击次数:1240 更新时间:2018-2-7 18:36:42  【打印此页

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;
}                           


 

提示
郴维网为您提供各类专业服务:
软件开发,电脑配件销售,WIFI路由器销售,上门电脑维修,上门安装系统,系统安装,软、硬件安装,电脑除尘清灰,显示器维修,WIFI安装调试,服务器维护,数据恢复,密码破解,网络布线,网络检修,打印机维修,打印机加碳粉,苹果电脑安装系统,苹果电脑安装双系统,监控安装维护,电脑外包,笔记本电脑维修,餐饮、美容行业软件安装 等。。。。。。
点击次数:1240 更新时间:2018-2-7 18:36:42  【打印此页
关键词推荐:郴州电脑城 郴州电脑维修公司 维修电脑公司 郴州软件开发 上门电脑维修 上门安装系统 笔记本电脑维修 郴州打印机维修 打印机加碳粉 电脑安装双系统 苹果电脑双系统 液晶显示器维修 联想笔记本维修 联想笔记本维修电话 戴尔笔记本维修电话 郴州戴尔笔记本维修 戴尔笔记本郴州维修点 华硕笔记本维修点 郴州华硕笔记本维修 郴州笔记本上网维修