C++文件读写核心是fstream流类,按需选用ifstream/ofstream/fstream,打开后检查is_open(),支持getline逐行读、>>分词读、read/write二进制操作,写入默认覆盖,追加需ios::app,二进制须加ios::binary模式。

C++ 读取和写入文件,核心就是用 fstream(文件流),它把文件当“流”来处理,和 cin/cout 用法很像,学起来不难。
打开文件:用 ifstream、ofstream 或 fstream
根据操作类型选对流类:
-
ifstream:只读文件(input file stream) -
ofstream:只写文件(output file stream) -
fstream:可读可写(更灵活,但注意打开模式)
打开时推荐用构造函数或 open(),并检查是否成功:
#include <fstream>
#include <iostream>
#include <string>
std::ifstream fin("data.txt");
if (!fin.is_open()) {
std::cerr <h3>读取文件:按行、按词、按<a style="color:#f60; text-decoration:underline;" title="字节" href="https://m.php.cn/zt/16298.html" target="_blank">字节</a>都行</h3>
<p>常用读取方式有三种,看需求选:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill10691" title="Livestream Script Generator"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="Livestream Script Generator" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill10691" title="Livestream Script Generator" class="overflowclass">Livestream Script Generator</a>
<p class="overflowclass">直播带货脚本:话术、节奏、互动、促单。适用于主播、电商运营、MCN机构。</p>
</div>
<a rel="nofollow" href="/xiazai/skill10691" title="Livestream Script Generator" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<ul>
<li>
<code>getline(fin, str)</code>:一行一行读(推荐,能读空格)</li>
<li>
<code>fin >> str</code>:按空白符分隔读(跳过空格/换行,类似 cin)</li>
<li>
<code>fin.get(ch)</code> 或 <code>fin.read(buf, n)</code>:逐字符或批量读字节(适合二进制)</li>
</ul>
<font color="#888">示例:逐行读取并打印</font><pre class="brush:php;toolbar:false;">std::string line;
while (std::getline(fin, line)) {
std::cout <h3>写入文件:输出流操作,和 cout 几乎一样</h3><p>用 <code>ofstream</code> 打开后,直接用 <code> 写入即可:</code></p>
- 默认是覆盖写入(
std::ofstream fout("out.txt")) - 想追加写入,加
std::ios::app模式:ofstream fout("out.txt", std::ios::app) - 写入失败可用
fout.fail()检查
std::ofstream fout("result.txt");
fout <h3>二进制文件操作:加 ios::binary 模式</h3><p>读写图片、音频、结构体等原始数据,必须用二进制模式,避免换行符被自动转换:</p>
- 打开时加上
std::ios::binary - 用
read()/write()配合reinterpret_cast处理内存块 - 注意结构体可能有内存对齐,跨平台慎用
int val = 12345;
std::ofstream binout("data.bin", std::ios::binary);
binout.write(reinterpret_cast<const char>(&val), sizeof(val));
binout.close();
</const>
基本上就这些。关键是选对流类型、开对模式、读写后检查状态、用完记得 close —— 不复杂但容易忽略。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










