在C++中,你可以使用多种方法来读取和写入文件。最常见的方法是使用C++标准库中的<fstream>
头文件,它提供了ifstream
(用于读取文件)和ofstream
(用于写入文件)类。下面是一些基本示例来展示如何使用这些类来读取和写入文件。
ifstream
(用于读取文件)
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt"); // 打开文件
if (file.is_open()) {
std::string line;
while (getline(file, line)) { // 逐行读取
std::cout << line << std::endl; // 输出到控制台
}
file.close(); // 关闭文件
} else {
std::cerr << "无法打开文件" << std::endl;
}
return 0;
}
ofstream
(用于写入文件)
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream file("example.txt"); // 打开文件,如果文件不存在则创建它
if (file.is_open()) {
file << "Hello, World!" << std::endl; // 写入字符串到文件
file.close(); // 关闭文件
} else {
std::cerr << "无法打开文件" << std::endl;
}
return 0;
}
同时读取和写入文件(追加模式)
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream file("example.txt", std::ios::app); // 打开文件以追加内容
if (file.is_open()) {
file << "追加的文本。" << std::endl; // 追加内容到文件末尾
file.close(); // 关闭文件
} else {
std::cerr << "无法打开文件" << std::endl;
}
return 0;
}
一、核心类和函数功能讲解
fstream:文件输入输出类。表示文件级输入输出流(字节流);
ifstream:文件输入类。表示从文件内容输入,也就是读文件;
ofstream:文件输出类。表示文件输出流,即文件写。
seekg():输入文件指针跳转函数。表示将输入文件指针跳转到指定字节位置‘
seekp():输出文件指针跳转函数。表示将输出文件指针跳转到指定位置。
下面将通过总结一个读写*.txt文件来演示上述输入输出类和文件跳转函数用法。
二、简单示例
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdio>
struct planet
{
char name[20];
double population;
double g;
}p1;
int main()
{
using namespace std;
/*读文件*/
int ct = 0; //计数
fstream finout; //文件读和写字节流
finout.open("test1.txt", ios_base::in | ios_base::out | ios_base::binary); //二进制读和写
if (!finout.is_open())
{
cout << "open file E:\\1TJQ\\test1.txt fail!";
system("pause");
return false;
}
finout.seekg(0); //输入流文件跳转指针,回到文件起始位置
cout << "show red file\n";
while (finout.read((char *) &p1,sizeof p1))
{
cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;
}
if (finout.eof())
finout.clear(); //清空结尾eof标志,可以再次打开该文件
/*写文件*/
streampos place = 3 * sizeof p1; //转换到streampos类型
finout.seekg(place); //随机访问
if (finout.fail())
{
cerr << "error on attempted seek\n";
system("pause");
exit(EXIT_FAILURE);
}
finout.read((char *)&p1, sizeof p1);
cout << "\n\nshow writed file\n";
cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;
if (finout.eof())
finout.clear(); //清楚eof标志
memcpy(p1.name, "Name1", sizeof("Name1"));
p1.population = 66.0;
p1.g == 55.0;
finout.seekp(place);
finout.write((char *)&p1, sizeof p1) << flush;
if (finout.fail())
{
cerr << "error attempted write\n";
system("pause");
exit(EXIT_FAILURE);
}
/*显示修改后的文件内容*/
ct = 0;
finout.seekg(0);
cout << "\n\nshow revised file\n";
while (finout.read((char *) &p1,sizeof p1))
{
cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;
}
system("pause");
return 0;
}