GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.runoob.com — C++ 文件和流 | 菜鸟教程
C++ 教程
C++ 教程
C++ 简介
C++ 环境设置
C++ 基本语法
C++ 注释
C++ 数据类型
C++ 变量类型
C++ 变量作用域
C++ 常量
C++ 修饰符类型
C++ 存储类
C++ 运算符
C++ 循环
C++ 判断
C++ 函数
C++ 数字
C++ 数组
C++ 字符串
C++ 指针
C++ 引用
C++ 日期 & 时间
C++ 基本的输入输出
C++ 结构体(struct)
C++ vector 容器
C++ 数据结构
C++ 面向对象C++ 类 & 对象 C++ 继承 C++ 重载运算符和重载函数 C++ 多态 C++ 数据抽象 C++ 数据封装 C++ 接口(抽象类)C++ 高级教程C++ 文件和流 C++ 异常处理 C++ 动态内存 C++ 命名空间 C++ 模板 C++ 预处理器 C++ 信号处理 C++ 多线程 C++ Web 编程C++ 资源库C++ STL 教程 C++ 导入标准库 C++ 标准库 C++ 有用的资源 C++ 实例 C++ 测验 C++ <iostream> C++ <fstream> C++ <sstream> C++ <iomanip> C++<array>
C++ <vector>
C++ <list>
C++ <forward_list>
C++ <deque>
C++ <stack>
C++ <queue>
C++ <priority_queue>
C++ <set>
C++ <unordered_set>
C++ <map>
C++ <unordered_map>
C++ <bitset>
C++ <algorithm>
C++ <iterator>
C++ <functional>
C++ <numeric>
C++ <complex>
C++ <valarray>
C++ <cmath>
C++ <string>
C++ <regex>
C++ <ctime>
C++ <chrono>
C++ <thread>
C++ <mutex>
C++ <condition_variable>
C++ <future>
C++ <atomic>
C++ <type_traits>
C++ <typeinfo>
C++ <exception>
C++ <stdexcept>
C++ <cstdio>
C++ <cstdint>
C++ <memory>
C++ <new>
C++ <utility>
C++ <random>
C++ <locale>
C++ <codecvt>
C++ <cassert>
C++ <cwchar>
C++ <climits>
C++ <cfloat>
C++ <cstdlib>
C++ <numbers>
C++ OpenCV
C++ 文件和流在前面的章节中,我们使用过 C++ 标准库中的 除了标准输入输出,C++ 还支持文件操作,可以将数据保存到文件中,也可以从文件中读取已有的数据。 C++ 通过
使用文件流时,需要包含头文件: #include <fstream> 如果程序还需要使用 #include <iostream> 例如,创建一个用于写入文件的对象: std::ofstream outfile("example.txt");
以上代码尝试打开 打开文件在读取或写入文件之前,首先需要打开文件。 C++ 可以通过文件流对象的构造函数直接打开文件,也可以先创建对象,再使用 方式一:创建对象时打开文件 std::ofstream outfile("example.txt");
方式二:使用 open() 方法 std::ofstream outfile;
outfile.open("example.txt");
这两种方式都可以用于打开文件,第一种写法更简洁。
void open(
const char* filename,
std::ios::openmode mode
);
其中:
上述是简化后的函数声明,不同文件流类具有不同的默认打开模式。现代 C++ 也支持使用 文件打开模式C++ 提供了多种文件打开模式,可以根据需要进行选择。
多个模式可以使用按位或运算符 例如,以写入模式打开文件,并清空原有内容: std::ofstream outfile;
outfile.open("file.dat", std::ios::out | std::ios::trunc);
如果希望保留文件原有内容,并将新内容追加到末尾,可以使用: std::ofstream outfile;
outfile.open("file.dat", std::ios::app);
如果需要同时读取和写入文件,可以使用 std::fstream file;
file.open("file.dat", std::ios::in | std::ios::out);
注意:上述双向读写模式通常要求文件已经存在。如果需要创建新文件,可以根据实际需求组合写入模式,但应注意 默认情况下,三个文件流类通常使用以下打开模式:
检查文件是否打开成功文件打开操作并不一定成功。例如,文件不存在、路径错误或者没有访问权限,都可能导致打开失败。 可以使用 实例#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("example.txt");
if (!infile.is_open()) {
cout << "文件打开失败!" << endl;
return 1;
}
cout << "文件打开成功!" << endl;
infile.close();
return 0;
} 如果当前工作目录中不存在 文件打开失败! 除了 关闭文件文件使用完毕后,可以通过 其基本调用方式如下: outfile.close(); 关闭文件时,文件流会尝试完成必要的缓冲区刷新,并解除与文件的关联。 C++ 文件流对象还具有自动资源管理机制。当局部文件流对象离开作用域并被销毁时,关联的文件也会自动关闭。 例如: {
std::ofstream file("example.txt");
file << "Hello C++";
} // file 离开作用域,自动关闭文件
因此,并不是每次都必须显式调用 写入文件在 C++ 中,可以使用输出文件流 使用方法与通过 实例#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// 创建并打开文件
ofstream outfile("example.txt");
if (!outfile) {
cerr << "无法打开文件!" << endl;
return 1;
}
// 向文件写入内容
outfile << "Hello C++" << '\n';
outfile << "欢迎学习 C++ 文件操作" << '\n';
outfile << "数字:" << 100 << '\n';
// 关闭文件
outfile.close();
if (!outfile) {
cerr << "文件写入或关闭失败!" << endl;
return 1;
}
cout << "文件写入成功!" << endl;
return 0;
} 程序正常执行后,屏幕输出: 文件写入成功! 同时,在当前工作目录下生成 Hello C++ 欢迎学习 C++ 文件操作 数字:100 注意:如果 追加写入文件如果不希望清空原有内容,而是想在文件末尾增加数据,可以使用 实例#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// 以追加模式打开文件
ofstream outfile("example.txt", ios::app);
if (!outfile) {
cerr << "无法打开文件!" << endl;
return 1;
}
outfile << "这是一行追加的内容。" << '\n';
outfile.close();
if (!outfile) {
cerr << "文件写入失败!" << endl;
return 1;
}
cout << "内容追加成功!" << endl;
return 0;
} 程序每执行一次,就会尝试在文件末尾追加一行内容,而不会主动清空已有数据。 读取文件在 C++ 中,可以使用输入文件流 常见的读取方式包括:
使用 >> 读取数据下面演示如何读取文件中的两个整数。 实例#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// 先创建测试文件
{
ofstream outfile("numbers.txt");
if (!outfile) {
cerr << "创建文件失败!" << endl;
return 1;
}
outfile << "100 200" << '\n';
outfile.close();
if (!outfile) {
cerr << "写入测试文件失败!" << endl;
return 1;
}
}
ifstream infile("numbers.txt");
if (!infile) {
cerr << "读取文件失败!" << endl;
return 1;
}
int a, b;
if (infile >> a >> b) {
cout << "a = " << a << endl;
cout << "b = " << b << endl;
} else {
cerr << "文件数据格式错误!" << endl;
return 1;
}
return 0;
} 执行结果: a = 100 b = 200 流提取运算符 如果读取字符串,例如 使用 getline() 逐行读取如果需要读取包含空格的文本,可以使用 实例#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile("example.txt");
if (!infile) {
cerr << "无法打开文件!" << endl;
return 1;
}
string line;
// 逐行读取,直到文件结束或读取失败
while (getline(infile, line)) {
cout << line << endl;
}
if (infile.bad()) {
cerr << "读取文件时发生错误!" << endl;
return 1;
}
infile.close();
return 0;
} 如果文件中包含以下内容: Hello C++ Welcome to C++ programming This is a text file. 程序正常运行时,会逐行输出对应的文本。
注意:当使用 读取 & 写入实例下面通过一个完整实例,演示如何将用户输入的信息写入文件,然后重新打开文件并读取其中的内容。 程序会要求用户输入姓名和年龄,将数据保存到 实例#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name;
int age;
// 获取用户输入
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your age: ";
if (!(cin >> age)) {
cerr << "Invalid age!" << endl;
return 1;
}
// 以写入模式打开文件
ofstream outfile("afile.dat");
if (!outfile) {
cerr << "Cannot open file for writing!" << endl;
return 1;
}
// 写入数据
outfile << name << '\n';
outfile << age << '\n';
// 关闭文件并检查状态
outfile.close();
if (!outfile) {
cerr << "Failed to write file!" << endl;
return 1;
}
// 以读取模式重新打开文件
ifstream infile("afile.dat");
if (!infile) {
cerr << "Cannot open file for reading!" << endl;
return 1;
}
string readName;
int readAge;
// 读取姓名
if (!getline(infile, readName)) {
cerr << "Failed to read name!" << endl;
return 1;
}
// 读取年龄
if (!(infile >> readAge)) {
cerr << "Failed to read age!" << endl;
return 1;
}
// 输出文件内容
cout << "Reading from the file" << endl;
cout << "Name: " << readName << endl;
cout << "Age: " << readAge << endl;
infile.close();
return 0;
} 当程序被编译和执行时,假设输入姓名 Zara,年龄为 9,运行结果如下: Enter your name: Zara Enter your age: 9 Reading from the file Name: Zara Age: 9 程序执行成功后, Zara 9 程序说明:
这个实例采用先写入、再关闭、最后重新打开读取的方式,便于初学者理解文件输入输出过程。 如果需要在同一个文件流对象中进行读写,可以使用 文件位置指针文件流会维护与读写位置有关的状态,用于确定下一次从哪里读取数据,或者向哪里写入数据。 常用的文件位置操作函数包括:
其中,字母 seekg() 和 seekp()
常见的定位基准包括:
以下代码展示了常见的定位方式: 实例// 假设 fileObject 是已打开的文件输入流
// 定位到文件开头
fileObject.seekg(0, ios::beg);
// 从文件开头向后移动 n 个位置单位
fileObject.seekg(n, ios::beg);
// 从当前位置向后移动 n 个位置单位
fileObject.seekg(n, ios::cur);
// 从文件末尾向前移动 n 个位置单位
fileObject.seekg(-n, ios::end);
// 定位到文件末尾
fileObject.seekg(0, ios::end); 上述代码用于说明函数的调用方式,其中 注意:在二进制文件中,常见实现允许按字节偏移进行定位;文本模式下可能存在换行符转换或编码相关问题,不应简单地将所有文件位置都理解为可任意计算的字节索引。 文件位置操作实例下面创建一个二进制文件,写入字符串 实例#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// 创建二进制文件
ofstream outfile("position.dat", ios::binary);
if (!outfile) {
cerr << "创建文件失败!" << endl;
return 1;
}
outfile << "ABCDEFGHIJ";
outfile.close();
if (!outfile) {
cerr << "写入文件失败!" << endl;
return 1;
}
// 以二进制模式读取文件
ifstream infile("position.dat", ios::binary);
if (!infile) {
cerr << "打开文件失败!" << endl;
return 1;
}
char ch;
// 定位到偏移量为 4 的位置
infile.seekg(4, ios::beg);
if (!infile.get(ch)) {
cerr << "读取文件失败!" << endl;
return 1;
}
cout << "读取的字符:" << ch << endl;
// 返回到文件开头
infile.seekg(0, ios::beg);
if (!infile.get(ch)) {
cerr << "读取文件失败!" << endl;
return 1;
}
cout << "第一个字符:" << ch << endl;
infile.close();
return 0;
} 执行结果: 读取的字符:E 第一个字符:A 因为文件位置从 0 开始计算,所以偏移量为 4 的位置对应第 5 个字符 在使用 获取文件大小对于普通二进制文件,可以结合 实例#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile("position.dat", ios::binary | ios::ate);
if (!infile) {
cerr << "无法打开文件!" << endl;
return 1;
}
// 打开文件后,读取位置位于文件末尾
streampos size = infile.tellg();
if (size == streampos(-1)) {
cerr << "获取文件大小失败!" << endl;
return 1;
}
cout << "文件大小:" << size << " 字节" << endl;
infile.close();
return 0;
} 如果 文件大小:10 字节 在常见平台和普通文件上,二进制流末尾位置可以用于获得文件的字节长度。对于现代 C++ 项目,也可以使用 C++17 提供的 文件操作注意事项在实际开发中,文件操作还需要注意以下几个问题:
对于普通文本文件,推荐使用 对于需要随机访问的二进制文件,可以结合
AI 思考中...
| ||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |