[C++]文件打开读取示例代码

本文通过示例1和示例2详细介绍了如何在C++中进行文件打开与读取的操作,涵盖基本的文件读取流程和常见方法。

示例1:

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
	ifstream file;
	file.open("test.txt");
	char ch;
	int ch_count = 0;

	while (file >> ch)
	{
		ch_count++;
	}
	file.close();
	cout << "There are " << ch_count << " charactors in the file." << endl;
	return 0;
}

示例2:

/*
 * ex6-9.cpp
 *
 *  Created on: Nov 11, 2016
 *      Author: Jamienstar
 */

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

struct contributor
{
	string name;
	double contribution;
};

int main(void)
{
	ifstream file;
	file.open("contributors.txt");

	int contributor_num;
	file >> contributor_num;
	file.get();
	contributor *contibutors = new contributor[contributor_num];
	int i = 0;
	int grand_count = 0;
	while (i < contributor_num)
	{
		getline(file, contibutors[i].name
<think>我们被要求提供C++文本文件读取示例代码,并且需要参考之前提供的引用内容。 根据引用内容,特别是引用[3]和引用[4],我们可以看到读取文本文件的基本步骤: 1. 包含必要的头文件:<iostream>, <fstream>, <string> 2. 使用ifstream类打开文件,并检查文件是否成功打开。 3. 逐行读取文件内容(使用getline函数)。 4. 对每一行进行解析或处理(例如,跳过空行或注释行,解析键值对等)。 5. 关闭文件(虽然ifstream在析构时会自动关闭,但显式关闭是一个好习惯)。 我们将按照这些步骤编写一个示例代码,该代码打开一个文本文件,逐行读取并输出到控制台。 注意:我们不需要解析键值对,只需要演示读取并输出每一行。但为了演示更完整,我们可以增加一些基本处理,例如跳过空行(但这里我们选择输出所有行,包括空行,但可以用注释说明如何跳过空行)。 另外,根据引用[2]和引用[4],我们还可以了解文件打开模式(ios::in)以及文件流的状态检查。 下面是一个简单的读取文本文件并打印每一行内容的示例代码: </think>### C++ 文本文件读取示例代码解析 以下是一个完整的 C++ 文本文件读取示例,包含详细注释和错误处理:[^3][^4] ```cpp #include <iostream> #include <fstream> #include <string> int main() { // 创建输入文件流对象 std::ifstream inputFile; // 打开文件(两种等效方式) inputFile.open("data.txt"); // 方式1:默认读取模式 // std::ifstream inputFile("data.txt"); // 方式2:构造函数直接打开 // 检查文件是否成功打开 if (!inputFile.is_open()) { // 等效于 if(!inputFile) std::cerr << "错误:无法打开文件!" << std::endl; return 1; // 返回非零错误码 } std::string line; int lineCount = 0; // 逐行读取文件内容 while (std::getline(inputFile, line)) { lineCount++; // 示例处理:跳过空行和注释行 if (line.empty() || line[0] == '#') { std::cout << "[跳过行 " << lineCount << "]" << std::endl; continue; } // 输出有效行内容 std::cout << "行" << lineCount << ": " << line << std::endl; } // 检查读取过程是否出错 if (!inputFile.eof()) { std::cerr << "警告:未到达文件末尾即中断读取!" << std::endl; } // 关闭文件(析构函数会自动关闭,但显式关闭更规范) inputFile.close(); return 0; } ``` #### 关键解析: 1. **文件流对象** - `std::ifstream` 专用于读取文件 [^2] - 构造时可直接打开:`std::ifstream 文件名("路径")` 2. **打开模式**(默认 `ios::in`) ```cpp inputFile.open("data.txt", std::ios::in); // 显式指定读取模式 ``` 其他常用模式:`std::ios::binary`(二进制), `std::ios::ate`(初始定位到末尾)[^2] 3. **读取方法对比** | 方法 | 适用场景 | 示例 | |------|----------|------| | `getline()` | 逐行读取文本 | `while(getline(file, line))` | | `>>` 操作符 | 格式化读取 | `file >> intValue >> stringValue` | | `read()` | 二进制读取 | `file.read(buffer, size)` | 4. **错误处理要点** - `is_open()` 检查文件是否成功打开 - `eof()` 检测是否正常到达文件末尾 - 每次操作后检查流状态:`if(!inputFile) { /* 处理错误 */ }` #### 注意事项: 1. 文件路径可以是: - 绝对路径:`"C:/data/config.txt"` - 相对路径(相对于可执行文件位置):`"../data.txt"` 2. 跨平台路径分隔符:建议使用正斜杠 `/` 3. 资源管理:遵循 **RAII原则**,文件流对象超出作用域自动关闭[^5] > **示例文件 `data.txt` 内容** > ``` > # 配置文件示例 > username=admin > timeout=30 > > language=zh_CN > ``` > **输出结果** > ``` > [跳过行 1] > 行2: username=admin > 行3: timeout=30 > [跳过行 4] > 行5: language=zh_CN > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值