写读文件
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt"); // 创建输出文件对象并打开文件
if (outFile.is_open()) {
outFile << "Hello, world!\n"; // 向文件写入内容
outFile.close(); // 关闭文件
}
ifstream inFile("example.txt"); // 创建输入文件对象并打开文件
string content;
if (inFile.is_open()) {
while (getline(inFile, content)) { // 逐行读取文件内容
cout << content << endl;
}
inFile.close(); // 关闭文件
}
return 0;
}
文件指针的移动
可以通过 seekg()
和 seekp()
来移动输入或输出文件流中的位置,并通过 tellg()
和 tellp()
来获取当前位置。
ifstream inFile("example.txt");
inFile.seekg(10); // 移动到文件的第10个字节
int pos = inFile.tellg(); // 获取当前位置
cout << "Current position: " << pos << endl;
完整的文件写入实例
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file("example.txt", ios::in | ios::out); // 打开文件,允许读写
if (!file.is_open()) {
cerr << "Failed to open file!" << endl;
return 1;
}
file.seekp(15); // 移动写指针到第10个字节
file << "New data\n"; // 从第10个字节开始写入新内容
file << "new line\n";
file.close();
return 0;
}