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
指向的文件中size
和count
参数允许以数据块的形式写入数据,而不是一次写入一个字节
使用方法:
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
结构体地写入数组