自学内容网 自学内容网

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


原文地址:https://blog.csdn.net/weixin_41598714/article/details/143059138

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!