- C++
C++文件读写操作教程
- 2025-4-14 20:41:08 @
以下是一个C++文件读写操作的教程:
相关头文件和类
- 头文件:在C++ 中进行文件读写操作,需要包含
<fstream>
头文件。 - 相关类:
ifstream
:用于从文件中读取数据(输入文件流)。ofstream
:用于向文件中写入数据(输出文件流)。fstream
:既可以读取文件,也可以写入文件(输入输出文件流)。
文件打开与关闭
- 打开文件:可以通过文件流对象的
open
成员函数来打开文件,打开文件时需要指定文件路径和打开模式。例如:
std::ifstream infile;
infile.open("example.txt", std::ios::in); // 以只读模式打开文件
- 关闭文件:使用文件流对象的
close
成员函数关闭文件,以释放系统资源。例如:
infile.close();
文件写入操作
- 写入文本文件:创建
ofstream
对象,指定打开模式为ios::out
,如果文件不存在则创建,如果文件存在则覆盖原有内容。然后可以使用<<
操作符将数据写入文件。示例如下:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outfile("output.txt");
if (!outfile.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
outfile << "Hello, World!" << std::endl;
outfile << "This is a test." << std::endl;
outfile.close();
return 0;
}
- 写入二进制文件:打开文件时指定
ios::binary
模式,对于自定义数据类型,使用write
成员函数将数据写入文件。示例如下:
#include <iostream>
#include <fstream>
class Person {
public:
char name[64];
int age;
};
int main() {
Person p = { "张三", 18 };
std::ofstream outfile("person.bin", std::ios::out | std::ios::binary);
if (!outfile.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
outfile.write(reinterpret_cast<const char*>(&p), sizeof(Person));
outfile.close();
return 0;
}
文件读取操作
- 读取文本文件:创建
ifstream
对象,以ios::in
模式打开文件。可以使用>>
操作符按格式读取数据,或者使用getline
函数按行读取数据。示例如下:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream infile("example.txt");
if (!infile.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
infile.close();
return 0;
}
- 读取二进制文件:打开文件时指定
ios::binary
模式,使用read
成员函数读取数据到缓冲区。示例如下:
#include <iostream>
#include <fstream>
class Person {
public:
char name[64];
int age;
};
int main() {
Person p;
std::ifstream infile("person.bin", std::ios::in | std::ios::binary);
if (!infile.is_open()) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
infile.read(reinterpret_cast<char*>(&p), sizeof(Person));
infile.close();
std::cout << "姓名:" << p.name << ", 年龄:" << p.age << std::endl;
return 0;
}
文件定位
- 移动文件指针:使用
seekg
(用于输入流)或seekp
(用于输出流)函数来移动文件指针。例如,infile.seekg(10);
将输入文件流的指针移动到第10个字节的位置。 - 获取当前文件指针位置:使用
tellg
(用于输入流)或tellp
(用于输出流)函数获取当前文件指针的位置。例如,int pos = infile.tellg();
可以获取当前输入文件流指针的位置。
错误处理
- 检查文件是否成功打开:在打开文件后,通过文件流对象的
is_open
成员函数检查文件是否成功打开。如果返回false
,则表示打开失败,需要进行相应的错误处理。 - 检查文件流状态:可以使用文件流对象的
good
、eof
、fail
和bad
等成员函数来检查文件流的状态,以判断文件操作是否出现错误或到达文件末尾等情况。例如,while (!infile.eof())
可以用于判断是否到达文件末尾。
19 条评论
-
admin SU @ 2025-4-17 21:38:13
#include <iostream> #include <fstream> int main() { // 打开一个名为 log.txt 的文件,用于写入日志信息 std::ofstream log_file("log.txt"); // 打开一个名为 input.txt 的文件,用于读取输入信息 std::ifstream input_file("input.txt"); // 保存当前标准输出流 cout 的缓冲区指针 std::streambuf* org_cout = std::cout.rdbuf(); // 保存当前标准输入流 cin 的缓冲区指针 std::streambuf* org_cin = std::cin.rdbuf(); // 将标准输出流 cout 的缓冲区设置为 log_file 的缓冲区,实现输出重定向 std::cout.rdbuf(log_file.rdbuf()); // 将标准输入流 cin 的缓冲区设置为 input_file 的缓冲区,实现输入重定向 std::cin.rdbuf(input_file.rdbuf()); std::string input_line; // 从重定向后的输入流(即 input_file)读取一行信息 std::getline(std::cin, input_line); // 向重定向后的输出流(即 log_file)输出信息 std::cout << "从文件读取的内容: " << input_line << std::endl; // 将标准输出流 cout 的缓冲区恢复为原来保存的缓冲区,恢复正常输出 std::cout.rdbuf(org_cout); // 将标准输入流 cin 的缓冲区恢复为原来保存的缓冲区,恢复正常输入 std::cin.rdbuf(org_cin); // 关闭文件 log_file.close(); input_file.close(); return 0; }
若要在 C++ 里实现输入重定向,也就是把标准输入流 std::cin 重定向到文件,可参照输出重定向的思路,借助 std::streambuf 类达成。以下是在你给出的代码基础上添加输入重定向功能的示例: input-output-redirection C++ 输入输出重定向示例代码
#include <iostream> #include <fstream> int main() { // 打开一个名为 log.txt 的文件,用于写入日志信息 std::ofstream log_file("log.txt"); // 打开一个名为 input.txt 的文件,用于读取输入信息 std::ifstream input_file("input.txt"); // 保存当前标准输出流 cout 的缓冲区指针 std::streambuf* org_cout = std::cout.rdbuf(); // 保存当前标准输入流 cin 的缓冲区指针 std::streambuf* org_cin = std::cin.rdbuf(); // 将标准输出流 cout 的缓冲区设置为 log_file 的缓冲区,实现输出重定向 std::cout.rdbuf(log_file.rdbuf()); // 将标准输入流 cin 的缓冲区设置为 input_file 的缓冲区,实现输入重定向 std::cin.rdbuf(input_file.rdbuf()); std::string input_line; // 从重定向后的输入流(即 input_file)读取一行信息 std::getline(std::cin, input_line); // 向重定向后的输出流(即 log_file)输出信息 std::cout << "从文件读取的内容: " << input_line << std::endl; // 将标准输出流 cout 的缓冲区恢复为原来保存的缓冲区,恢复正常输出 std::cout.rdbuf(org_cout); // 将标准输入流 cin 的缓冲区恢复为原来保存的缓冲区,恢复正常输入 std::cin.rdbuf(org_cin); // 关闭文件 log_file.close(); input_file.close(); return 0; }
生成 input_output_redirection.cpp 代码解释: 文件打开:借助 std::ifstream 打开 input.txt 文件,用于读取输入内容;使用 std::ofstream 打开 log.txt 文件,用于写入日志信息。 保存原始缓冲区:分别保存 std::cin 和 std::cout 原来的缓冲区指针。 重定向输入输出:把 std::cin 的缓冲区设置为 input_file 的缓冲区,将 std::cout 的缓冲区设置为 log_file 的缓冲区。 读写操作:运用 std::getline 从 input_file 读取一行内容,然后将读取的内容和提示信息写入 log_file。 恢复原始缓冲区:在操作完成之后,把 std::cin 和 std::cout 的缓冲区恢复成原来的状态。 关闭文件:关闭打开的文件。 注意事项: 要保证 input.txt 文件存在,并且有可读权限。 重定向结束后,要记得恢复原始的缓冲区,不然后续的输入输出操作会受到影响。
-
2025-4-17 21:23:55@
#include <iostream> #include<fstream> // 使用文件输入输出流,对 cin 、 cout 语句适用 using namespace std; int main() { // 打开一个名为 log.txt 的文件,用于写入日志信息 ofstream output("out.txt"); // 保存当前标准输出流 cout 的缓冲区指针 streambuf* org_cout = cout.rdbuf(); // 将标准输出流 cout 的缓冲区设置为 log_file 的缓冲区,实现输出重定向 cout.rdbuf(output.rdbuf()); // 向重定向后的输出流(即 log_file)输出信息 cout << "Happy Spring!" << endl; // 将标准输出流 cout 的缓冲区恢复为原来保存的缓冲区,恢复正常输出 cout.rdbuf(org_cout); return 0; }
-
2025-4-17 21:19:47@
ifstream:用于从文件读取数据,它继承自 istream 类。在默认情况下,ifstream 以输入(读取)模式打开文件,即 std::ios::in 模式,这使得程序能够从指定的文件中读取各种类型的数据,如文本、数值等。 ofstream:用于向文件写入数据,继承自 ostream 类。ofstream 的默认打开模式为输出(写入)模式,也就是 std::ios::out 模式。当使用 ofstream 打开一个文件时,如果该文件已存在,其原有内容会被覆盖;若文件不存在,则会创建一个新文件用于写入数据。 fstream:既可以从文件读取数据,也可以向文件写入数据,继承自 iostream 类。fstream 的默认打开模式是 std::ios::in | std::ios::out,这意味着它同时具备输入和输出的功能。但需要注意的是,在默认模式下直接使用 fstream 打开文件进行读写操作时,可能需要根据具体的读写需求进一步调整文件指针的位置等操作,以避免数据读写混乱。
在
ifstream
使用in
模式打开文件时,如果文件不存在,不会报错,但会导致流处于错误状态。可以通过检查流对象的状态来判断文件是否成功打开,例如:#include <iostream> #include <fstream> int main() { std::ifstream inFile("nonexistent.txt", std::ios::in); if (!inFile) { std::cout << "文件打开失败,可能文件不存在。" << std::endl; // 可以在这里进行一些错误处理,比如返回错误码或者执行其他替代操作 } else { // 执行文件读取操作 inFile.close(); } return 0; }
在上述代码中,尝试以
in
模式打开一个不存在的文件nonexistent.txt
,通过!inFile
来判断文件是否成功打开,如果文件不存在,流处于错误状态,程序会输出提示信息。 -
2025-4-17 21:15:39@
#include <iostream> #include <fstream> int main() { // 打开一个名为 log.txt 的文件,用于写入日志信息 std::ofstream log_file("log.txt"); // 保存当前标准输出流 cout 的缓冲区指针 std::streambuf* org_cout = std::cout.rdbuf(); // 将标准输出流 cout 的缓冲区设置为 log_file 的缓冲区,实现输出重定向 std::cout.rdbuf(log_file.rdbuf()); // 向重定向后的输出流(即 log_file)输出信息 std::cout << "Happy Spring!" << std::endl; // 将标准输出流 cout 的缓冲区恢复为原来保存的缓冲区,恢复正常输出 std::cout.rdbuf(org_cout); return 0; }
#include <iostream> #include <fstream> int main() { std::ofstream log_file("log.txt"); if (!log_file.is_open()) { std::cerr << "Failed to open log file." << std::endl; return 1; } std::streambuf* org_cout = std::cout.rdbuf(); std::cout.rdbuf(log_file.rdbuf()); std::cout << "Happy Spring!" << std::endl; std::cout.rdbuf(org_cout); log_file.close(); return 0; }
-
2025-4-17 21:13:19@
#include<fstream> // 使用文件输入输出流,对 cin 、 cout 语句适用 using namespace std; int main() { ifstream fin("input.txt"); // 定义输入文件名 ofstream fout("out.txt"); // 定义输出文件名 // 从输入文件中读入数据 ,fin>>temp 主要是用于判断数据是否已经读完 //while (fin>>temp) sum=sum+temp; //fout<<sum<<endl; int n; fin>>n; int sum = 0; for(int i=1;i<=n;i++){ int a; fin>>a; sum += a; } fout<<sum; fin.close();fout.close(); // 关闭文件, return 0; }
-
2025-4-14 21:45:45@
-
2025-4-14 21:45:09@
#include<iostream> #include<cstdio> using namespace std; int main() { FILE* fin,*fout; fin = fopen("input.txt","r"); fout = fopen("output.txt","w"); int t; int sum = 0; while(fscanf(fin,"%d",&t) == 1){ sum += t; fprintf(fout,"%d\n",t); } fprintf(fout,"OUTPUT:%d\n",sum); cout<<endl; fclose(fin); fclose(fout); return 0; }
-
2025-4-14 21:34:47@
-
2025-4-14 21:33:50@
-
2025-4-14 21:30:52@
#include<iostream> #include<cstdio>//freopen() using namespace std; int main() { //FILE* f1 = FILE* f1 = freopen("poker.in", "r", stdin); FILE* f2 = freopen("poker.out", "w", stdout); /* 中间按原样写代码,什么都不用修改 */ int n; cin>>n; int sum = 0; for(int i = 1;i<=n;i++){ int a; cin>>a; sum+=a; } cout<<sum<<endl; fclose(stdin); fclose(stdout); return 0; }
-
2025-4-14 21:15:01@
在 C++ 里,文件操作属于很基础且重要的内容,它能让程序和外部文件进行交互,实现数据的存储和读取。C++ 提供了一系列的类和函数用于文件操作,这些类和函数主要在
<fstream>
头文件中定义。下面为你详细介绍 C++ 文件操作相关函数。1. 引入必要的头文件和命名空间
#include <iostream> #include <fstream> using namespace std;
#include <iostream>
:提供标准输入输出流的功能。#include <fstream>
:提供文件流的功能,是进行文件操作的核心头文件。using namespace std;
:使用标准命名空间,避免每次使用标准库中的类和函数时都要加上std::
前缀。
2. 文件流类
在
<fstream>
头文件中,有三个主要的文件流类:ifstream
:用于从文件读取数据,继承自istream
。ofstream
:用于向文件写入数据,继承自ostream
。fstream
:既可以从文件读取数据,也可以向文件写入数据,继承自iostream
。
3. 打开文件
打开文件是进行文件操作的第一步,可使用文件流对象的
open
函数,也可以在创建对象时直接指定文件名和打开模式。3.1 使用
open
函数ofstream outFile; outFile.open("example.txt", ios::out); if (!outFile.is_open()) { cout << "无法打开文件!" << endl; return 1; }
3.2 在创建对象时指定文件名和打开模式
ifstream inFile("example.txt", ios::in); if (!inFile.is_open()) { cout << "无法打开文件!" << endl; return 1; }
3.3 打开模式
ios::in
:以输入模式打开文件,用于读取数据。ios::out
:以输出模式打开文件,用于写入数据。若文件不存在则创建,若存在则清空原有内容。ios::app
:以追加模式打开文件,新写入的数据会追加到文件末尾。ios::binary
:以二进制模式打开文件,适用于处理二进制数据。ios::trunc
:若文件已存在,打开时会清空原有内容。ios::ate
:打开文件后将文件指针定位到文件末尾。
4. 写入文件
使用
ofstream
或fstream
向文件写入数据,可使用<<
操作符,和向标准输出cout
写入数据的方式类似。ofstream outFile("example.txt", ios::out); if (outFile.is_open()) { outFile << "Hello, World!" << endl; outFile << "这是一个文件写入示例。" << endl; outFile.close(); }
5. 读取文件
使用
ifstream
或fstream
从文件读取数据,有多种读取方式。5.1 使用
>>
操作符逐词读取ifstream inFile("example.txt", ios::in); if (inFile.is_open()) { string word; while (inFile >> word) { cout << word << endl; } inFile.close(); }
5.2 使用
getline
函数逐行读取ifstream inFile("example.txt", ios::in); if (inFile.is_open()) { string line; while (getline(inFile, line)) { cout << line << endl; } inFile.close(); }
6. 二进制文件读写
对于二进制文件的读写,需要使用
ios::binary
打开模式,并使用read
和write
函数。6.1 二进制文件写入
#include <iostream> #include <fstream> using namespace std; int main() { ofstream binaryOutFile("binary_example.bin", ios::out | ios::binary); if (binaryOutFile.is_open()) { int num = 123; binaryOutFile.write(reinterpret_cast<const char*>(&num), sizeof(num)); binaryOutFile.close(); } return 0; }
6.2 二进制文件读取
#include <iostream> #include <fstream> using namespace std; int main() { ifstream binaryInFile("binary_example.bin", ios::in | ios::binary); if (binaryInFile.is_open()) { int num; binaryInFile.read(reinterpret_cast<char*>(&num), sizeof(num)); cout << "读取的数字是:" << num << endl; binaryInFile.close(); } return 0; }
7. 文件定位
可以使用
seekg
(用于输入流)和seekp
(用于输出流)函数来移动文件指针,使用tellg
和tellp
函数来获取文件指针的当前位置。7.1 移动文件指针
ifstream inFile("example.txt", ios::in); if (inFile.is_open()) { inFile.seekg(10); // 将文件指针移动到第 10 个字节的位置 char ch; inFile.get(ch); cout << "第 10 个字节的字符是:" << ch << endl; inFile.close(); }
7.2 获取文件指针位置
ifstream inFile("example.txt", ios::in); if (inFile.is_open()) { streampos pos = inFile.tellg(); // 获取文件指针的当前位置 cout << "文件指针的当前位置是:" << pos << endl; inFile.close(); }
8. 关闭文件
操作完成后,需要使用
close
函数关闭文件,以释放系统资源。ifstream inFile("example.txt", ios::in); if (inFile.is_open()) { // 进行文件读取操作 inFile.close(); }
9. 错误处理
在文件操作过程中,可能会出现各种错误,如文件无法打开、读取或写入失败等。可以使用文件流对象的状态标志来检查错误。
ifstream inFile("example.txt", ios::in); if (!inFile) { cout << "文件打开失败!" << endl; return 1; }
完整示例代码
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { // 写入文件 ofstream outFile("example.txt", ios::out); if (outFile.is_open()) { outFile << "Hello, World!" << endl; outFile << "这是一个文件写入示例。" << endl; outFile.close(); } // 读取文件 ifstream inFile("example.txt", ios::in); if (inFile.is_open()) { string line; while (getline(inFile, line)) { cout << line << endl; } inFile.close(); } return 0; }
通过以上内容,你可以掌握 C++ 中基本的文件操作方法,包括文件的打开、读写、定位、关闭以及错误处理等。
-
2025-4-14 21:13:04@
-
2025-4-14 21:12:50@
-
2025-4-14 21:05:14@
在C++ 中,对于文本文件,通常没有一个特定的ASCII码值来表示文件的结束。而是通过一些约定或函数来判断文件是否到达末尾。
在C++ 中,可以使用
eof()
函数来判断是否到达文件末尾。当读取到文件末尾时,eof()
函数会返回一个非零值(通常为真)。在ASCII码中,有一个字符叫做“文件结束符”(End Of File,EOF),其值通常被定义为 -1(在一些系统中可能有不同的定义)。但它并不是一个真正的字符,而是一个用于表示文件结束的特殊标记。在C++ 中,
getchar()
等函数在读取到文件末尾时会返回EOF
。对于二进制文件,同样也是通过特定的函数或标志来判断文件结束,而不是依赖某个特定的ASCII码值。因为二进制文件中可能包含各种数据,不能简单地用一个特定的ASCII码来表示文件结束。
-
2025-4-14 21:03:46@
在 C++ 里,文件读写操作是很常用的功能,它能让程序和外部文件进行交互,实现数据的持久化存储和读取。下面将为你详细且通俗易懂地介绍 C++ 文件读写操作。
1. 引入必要的头文件
在 C++ 中进行文件读写操作,需要包含
<fstream>
头文件,它定义了文件流相关的类和操作。同时,为了方便使用标准库中的函数和对象,我们使用using namespace std;
。#include <fstream> using namespace std;
2. 文件写入操作
2.1 创建输出文件流对象
要向文件写入数据,需要创建一个
ofstream
类型的对象。ofstream
代表输出文件流,用于将数据写入文件。ofstream outFile;
2.2 打开文件
使用
open
方法打开文件,同时指定文件路径和打开模式。打开模式有多种,常用的是ios::out
,表示以输出模式打开文件,如果文件不存在则创建,如果存在则清空原有内容。outFile.open("example.txt", ios::out);
2.3 检查文件是否成功打开
在打开文件后,需要检查文件是否成功打开。可以通过
is_open()
方法来判断。if (!outFile.is_open()) { cout << "无法打开文件!" << endl; return 1; }
2.4 写入数据
使用
<<
操作符向文件写入数据,就像向标准输出cout
写入数据一样。outFile << "Hello, World!" << endl; outFile << "这是一个文件写入示例。" << endl;
2.5 关闭文件
操作完成后,使用
close()
方法关闭文件,释放系统资源。outFile.close();
完整示例代码
#include <iostream> #include <fstream> using namespace std; int main() { ofstream outFile; outFile.open("example.txt", ios::out); if (!outFile.is_open()) { cout << "无法打开文件!" << endl; return 1; } outFile << "Hello, World!" << endl; outFile << "这是一个文件写入示例。" << endl; outFile.close(); return 0; }
3. 文件读取操作
3.1 创建输入文件流对象
要从文件读取数据,需要创建一个
ifstream
类型的对象。ifstream
代表输入文件流,用于从文件中读取数据。ifstream inFile;
3.2 打开文件
使用
open
方法打开文件,指定文件路径和打开模式,常用的是ios::in
,表示以输入模式打开文件。inFile.open("example.txt", ios::in);
3.3 检查文件是否成功打开
同样,使用
is_open()
方法检查文件是否成功打开。if (!inFile.is_open()) { cout << "无法打开文件!" << endl; return 1; }
3.4 读取数据
有多种方式可以从文件读取数据,下面介绍两种常见的方法:
3.4.1 使用
>>
操作符逐词读取string word; while (inFile >> word) { cout << word << endl; }
3.4.2 使用
getline()
函数逐行读取string line; while (getline(inFile, line)) { cout << line << endl; }
3.5 关闭文件
读取完成后,使用
close()
方法关闭文件。inFile.close();
完整示例代码
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream inFile; inFile.open("example.txt", ios::in); if (!inFile.is_open()) { cout << "无法打开文件!" << endl; return 1; } string line; while (getline(inFile, line)) { cout << line << endl; } inFile.close(); return 0; }
4. 二进制文件读写
4.1 二进制文件写入
在打开文件时,需要指定
ios::binary
模式。使用write()
方法写入二进制数据。#include <iostream> #include <fstream> using namespace std; int main() { ofstream binaryOutFile("binary_example.bin", ios::out | ios::binary); if (!binaryOutFile.is_open()) { cout << "无法打开文件!" << endl; return 1; } int num = 123; binaryOutFile.write(reinterpret_cast<const char*>(&num), sizeof(num)); binaryOutFile.close(); return 0; }
4.2 二进制文件读取
同样,在打开文件时指定
ios::binary
模式。使用read()
方法读取二进制数据。#include <iostream> #include <fstream> using namespace std; int main() { ifstream binaryInFile("binary_example.bin", ios::in | ios::binary); if (!binaryInFile.is_open()) { cout << "无法打开文件!" << endl; return 1; } int num; binaryInFile.read(reinterpret_cast<char*>(&num), sizeof(num)); cout << "读取的数字是:" << num << endl; binaryInFile.close(); return 0; }
5. 文件打开模式总结
ios::out
:以输出模式打开文件,用于写入数据。ios::in
:以输入模式打开文件,用于读取数据。ios::binary
:以二进制模式打开文件。ios::app
:以追加模式打开文件,新写入的数据会追加到文件末尾。ios::trunc
:如果文件已存在,打开时会清空原有内容。
通过上述步骤和示例代码,你可以掌握 C++ 中基本的文件读写操作,无论是文本文件还是二进制文件都能进行有效的读写。
-
2025-4-14 21:02:23@
#include<iostream> #include<cstdio>//freopen() using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); /* 中间按原样写代码,什么都不用修改 */ int a,b; cin>>a>>b; cout<<a+b; cout<<endl; fclose(stdin); fclose(stdout); return 0; }
-
2025-4-14 21:02:11@
-
2025-4-14 21:01:07@
-
2025-4-14 20:55:41@
- 1