【C++】文件操作

写读文件

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值