欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言之二进制读写文件

程序员文章站 2022-07-15 08:18:53
...

来源:我的博客站 OceanicKang |《C语言之二进制读写文件》

一、二进制读写

  • size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) - 读
  • size_t fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream) - 写
参数 含义
ptr 指向存放数据的内存块指针,该内存块的尺寸最小应该是 size * nmemb 个字节
size 指定要读取的每个元素的尺寸,最终尺寸等于 size * nmemb
nmemb 指定要读取的元素个数,最终尺寸等于 size * nmemb
stream 该参数是一个FILE对象的指针,指定一个待读取的文件流

返回值:

  • 返回值是实际读取到的元素个数(nmemb)
  • 如果返回值比nmemb参数的值小,表示可能读取到文件末尾或者有错误发生(可以使用feof函数或ferror函数进一步判断)

【注】文件是否以二进制形式打开并不影响二进制读写,或者说影响很小

二、例子

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 定义时间结构体
struct Date
{
    int year;
    int month;
    int day;
};

// 定义书籍结构体
struct Book
{
    char name[40];
    char author[40];
    struct Date date;
};

int main(void)
{
    struct Book *book_for_write = (struct Book *)malloc(sizeof(struct Book));
    struct Book *book_for_read = (struct Book *)malloc(sizeof(struct Book));
    if (book_for_write == NULL || book_for_read == NULL) {

        perror("申请内存失败!");
        exit(EXIT_FAILURE);

    }

    FILE *fp;

    // 写入 ************************************/
    struct tm *ptime;
    time_t t;
    time(&t);
    ptime = localtime(&t);

    strcpy(book_for_write -> name, "《书籍名称》");
    strcpy(book_for_write -> author, "OceanicKang");
    book_for_write -> date.year = 1900 + ptime -> tm_year;
    book_for_write -> date.month = 1 + ptime -> tm_mon;
    book_for_write -> date.day = ptime -> tm_mday;

    if ((fp = fopen("./test.txt", "w")) == NULL) {

        printf("打开文件失败!");
        exit(EXIT_FAILURE);

    }

    fwrite(book_for_write, sizeof(struct Book), 1, fp);

    fclose(fp);

    // 读取 ************************************/
    if ((fp = fopen("./test.txt", "r")) == NULL) {

        perror("打开文件失败!");
        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("时间:%d-%d-%d\n", book_for_read -> date.year, book_for_read -> date.month, book_for_read -> date.day);

    fclose(fp);

    free(book_for_write);
    free(book_for_read);

    return 0;
}