C/C++ 文件处理详解

在 C 和 C++ 中,文件处理是常见的任务之一,包括文件的读取、写入和操作。

1. C 文件处理

C 使用 stdio.h 提供的函数来处理文件操作。

a. 基本步骤

  1. 打开文件(fopen)。
  2. 读写文件(freadfwritefprintffscanffgetcfputc 等)。
  3. 关闭文件(fclose)。

b. 文件打开模式

模式 描述
"r" 只读模式,文件必须存在。
"w" 写模式,文件存在会清空内容。
"a" 追加模式,写入内容追加到末尾。
"r+" 读写模式,文件必须存在。
"w+" 读写模式,文件存在会清空内容。
"a+" 读写模式,写入内容追加到末尾。

c. 文件操作示例

写文件

c 复制代码
#include <stdio.h>

int main() {
	FILE *file = fopen("example.txt", "w");
	if (file == NULL) {
		perror("Error opending file");
		return 1;
	}

	fprintf(file, "Hello, World!\n");
	fclose(file);
	
	return 0;
}

读文件

c 复制代码
#include <stdio.h>

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

	char line[100];
	while (fgets(line, sizeof(line), file)) {
		printf("%s", line);
	}

	fclose(file);
	
	return 0;
}

二进制文件读写

c 复制代码
#include <stdio.h>

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

	int numbers[] = {1, 2, 3, 4, 5};
	fwrite(numbers, sizeof(int), 5, file);
	fclose(file);

	file = fopen("binary.dat", "rb");
	if (file == NULL) {
		perror("Error opening file");
		return 1;
	}

	int buffer[5];
	fread(buffer, sizeof(int), 5, file);

	for(int i=0; i<5; i++) {
		printf("%d ", buffer[i]);
	}

	fclose(file);
	return 0;
}

2. C++ 文件处理

C++ 使用 fstream 提供高级文件操作功能,头文件为 <fstream>

a. 基本步骤

  1. 创建文件流对象(std::ifstreamstd::ofstreamstd::fstream)。
  2. 打开文件(使用构造函数或 open 方法)。
  3. 读写文件。
  4. 关闭文件(自动关闭或显式调用 close)。

b. 文件流类型

类型 描述
std::ifstream 输入文件流,用于读文件。
std::ofstream 输出文件流,用于写文件。
std::fstream 通用文件流,读写文件。

c. 文件操作示例

写文件

cpp 复制代码
#include <fstream>
#include <iostream>

int main() {
	std::ofstream file("example.txt");
	if(!file) {
		std::cerr << "Error opening file" << std::endl;
		return 1;
	}

	file << "Hello, C++ World!" << std::endl;
	file.close();

	return 0;
}

读文件

cpp 复制代码
#include <fstream>
#include <iostream>
#include <string>

int main() {
	std::ifstream file("example.txt");
	if(!file) {
		std::cerr << "Error opening file" << std::endl;
		return 1;
	}

	std::string line;
	while (std::getline(file, line)) {
		std::cout << line << std::endl;
	}
	
	file.close();

	return 0;
}

二进制文件读写

cpp 复制代码
#include <fstream>
#include <iostream>

int main() {
	std::ofstream file("binary.dat", std::ios::binary);
	if (!file) {
		std::cerr << "Error opening file" << std::endl;
		return 1;
	}

	int numbers[] = {1, 2, 3, 4, 5};
	file.write(reinterpret_cast<char *>(numbers), sizeof(numbers));
	file.close();

	std::ifstream infile("binary.dat", std::ios::binary);
	if (!infile) {
		std::cerr << "Error opening file" << std::endl;
		return 1;
	}

	int buffer[5];
	infile.read(reinterpret_cast<char*>(buffer), sizeof(buffer));

	for(int n : buffer) {
		std::cout << n << " ";
	}

	infile.close();
	return 0;
}

3. 常见操作和注意事项

a. 文件指针

  • C 提供 ftellfseek 操作文件指针:
c 复制代码
fseek(file, 0, SEEK_END);		// 移动到文件末尾
long size = ftell(file);		// 获取文件大小
  • C++ 使用 seekgseekp
cpp 复制代码
file.seekg(0, std::ios::end);	// 读指针移动到末尾
std::streampos size = file.tellg();		// 获取文件大小

b. 文件状态检查

  • C 中可以用 ferror 检查错误。
  • C++ 提供流状态检查:
cpp 复制代码
if (file.fail()) {
	std::cerr << "Error occurred!" << std::endl;
}

c. 异常安全

C++ 文件流可以与异常处理结合使用:

cpp 复制代码
#include <fstream>
#include <iostream>
#include <stdexcept>

int main() {
	try {
		std::ifstream file("example.txt");
		if (!file) {
			throw std::runtime_error("Error opening file");
		}
		std::string content;
		while (std::getline(file, content)) {
			std::cout << content << std::endl;
		}
	} catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
	}
	return 0;
}

通过熟练掌握 C/C++ 文件处理技术,可以高效地完成各种文件操作。C 提供了基础功能,而 C++ 则提供了更安全和高级的文件流操作,适合复杂的应用场景。

相关推荐
艾莉丝努力练剑36 分钟前
【Linux:文件】Ext系列文件系统进阶
linux·运维·服务器·c++·文件系统·文件io·ext
kkeeper~1 小时前
0基础C语言积跬步之数据在内存中的存储
c语言·数据结构·算法
wabs6662 小时前
关于贪心算法的一些自我总结【力扣45.跳跃游戏II】【灵感来源:代码随想录】
算法·贪心算法·复盘
2401_876964132 小时前
【湖北专升本】2026湖北专升本真题PDF+备考资料汇总
数据结构·人工智能·经验分享·深度学习·算法·计算机视觉
basketball6163 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
qq3862461963 小时前
更新补发第6天:7天学会C语言,每天5分钟,不需要基础
c语言·for循环·循环语句·while循环·do-while循环
嗝o゚3 小时前
CANN GE 算子融合——融合算法与调度策略
算法·昇腾·cann·ge
小江的记录本3 小时前
【JVM虚拟机】垃圾回收GC:垃圾回收算法:标记-清除、标记-复制、标记-整理、分代收集(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·算法·安全·面试
Fre丸子_4 小时前
自定义文件夹选取功能
c++
Ulyanov5 小时前
用声明式语法重新定义Python桌面UI:QML+PySide6现代开发入门(一)
开发语言·python·算法·ui·系统仿真·雷达电子对抗仿真