
指导师老郭为您分享以下优质知识
在C语言中,二进制文件的读写操作主要通过以下两种方式实现:
一、使用标准库函数(推荐)
使用 `fopen` 函数以二进制模式打开文件,需添加 `ios::binary` 标志(在C++中)或模式参数 `wb`(在C中)。
写入数据
使用 `fwrite` 函数将数据写入文件,需指定数据类型、数据长度及文件指针。
关闭文件
使用 `fclose` 函数关闭文件流。
示例代码(C语言):
```c
include
int main() {
FILE *fp;
int number = 42;
float score = 95.5f;
char name[] = "张三";
// 以二进制模式打开文件
fp = fopen("data.bin", "wb");
if (fp == NULL) {
perror("无法打开文件");
return 1;
}
// 写入数据
fwrite(&number, sizeof(number), 1, fp);
fwrite(&score, sizeof(score), 1, fp);
fwrite(name, sizeof(name), 1, fp);
// 关闭文件
fclose(fp);
return 0;
}
```
二、使用C++的`fstream`库(更简洁)
C++提供了更高级的文件操作接口,使用 `ofstream` 和 `ifstream` 类可简化操作。
示例代码(C++):
```cpp
include
include
include
struct Person {
char name;
int age;
};
int main() {
Person person = {"张三", 18};
// 以二进制模式写入文件
std::ofstream outFile("person.bin", std::ios::binary);
if (!outFile) {
std::cerr