C 语言笔记1 - fwrite 函数

fwrite 函数

函数原型:

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

ptr:要写入的数据块的指针
size:每个数据项的字节大小
count:要写入的数据项的数量
stream:要写入的文件的 FILE 指针,该指针必须由 fopen 函数成功打开

参数之间的关系:

  • fwrite 函数将从 ptr 指向的内存位置开始,写入 size * count 个字节的数据到 stream 指向的文件中
  • sizecount 参数允许以数据块的形式写入数据,而不是一次写入一个字节

使用方法:

fopen 获取文件指针,使用 fwrite 写入数据,最后使用 fclose 关闭文件,释放资源

1.写入字符数组(字符串):

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

int main() {
    FILE *file = fopen("exp1.txt", "wb"); // 以二进制写入模式打开文件
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    char message[] = "Hello, world!";
    size_t length = strlen(message); // 获取字符串长度

    // 方式 1:按字符写入
    fwrite(message, sizeof(char), length, file);

    // 或者,方式 2:按整个字符串写入
    // fwrite(message, sizeof(message), 1, file);

    fclose(file);
    return 0;
}
  • 方式 1:按字符写入
    • size 设置为 sizeof(char),即 1 字节
    • count 设置为 length,即字符串的长度
    • 表示 fwrite 将逐个字符地写入字符串
  • 方式 2:按整个字符串写入
    • size 设置为 sizeof(message),即整个字符串的字节大小(包括结尾的 \0
    • count 设置为 1,表示一次写入整个字符串
    • 表示 fwrite 将整个字符串作为一个数据块写入

2.写入整型数组:

#include <stdio.h>

int main() {
    FILE *file = fopen("exp2.txt", "wb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int numbers[] = {1, 2, 3, 4, 5};
    size_t arrayLength = sizeof(numbers) / sizeof(numbers[0]); // 计算数组长度

    fwrite(numbers, sizeof(int), arrayLength, file);

    fclose(file);
    return 0;
}
  • size 设置为 sizeof(int),即每个整数的字节大小
  • count 设置为 arrayLength,即数组的长度
  • 表示 fwrite 将逐个整数地写入数组

3.写入结构体数组:

#include <stdio.h>

typedef struct {
    char name[20];
    int age;
} Person;

int main() {
    FILE *file = fopen("exp3.txt", "wb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    Person people[] = {
        {"A", 30},
        {"B", 25},
        {"C", 35}
    };
    size_t arrayLength = sizeof(people) / sizeof(people[0]);

    fwrite(people, sizeof(Person), arrayLength, file);

    fclose(file);
    return 0;
}
  • size 设置为 sizeof(Person),即每个 Person 结构体的字节大小
  • count 设置为 arrayLength,即数组的长度
  • 表示 fwrite 将逐个 Person 结构体地写入数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值