C++中的IO类

iostream

从流中读写数据

fstream

从文件中读写数据

ofstream outFile("example.txt");
if (!outFile.is_open())
{
	cerr << "Failed to open file!" << endl;
	return -1;
}
outFile << "Hello,C++ File I/O!\n";
outFile << "Number: " << 421 << "\n";
outFile << "PI: " << 3.14 << endl;

outFile.close();

追加写入模式

std::ofstream outFile("example.txt", std::ios::app); // 追加模式
outFile << "This line is appended.\n";
outFile.close();

写入二进制数据

#include <fstream>

struct Data {
    int id;
    double value;
};

int main() {
    Data data{1, 3.14};
    std::ofstream outFile("data.bin", std::ios::binary);

    if (!outFile) {
        std::cerr << "Failed to open binary file!" << std::endl;
        return 1;
    }

    outFile.write(reinterpret_cast<char*>(&data), sizeof(Data));
    outFile.close();
    return 0;
}

文件读取

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream inFile("example.txt");

    if (!inFile.is_open()) {
        std::cerr << "Failed to open file!" << std::endl;
        return 1;
    }

    std::string line;
    // 逐行读取(方法1:>> 运算符)
    while (inFile >> line) { // 默认以空格分隔
        std::cout << line << " ";
    }
    std::cout << std::endl;

    // 重新打开文件(因为上面已经读到末尾)
    inFile.clear(); // 清除错误标志
    inFile.seekg(0); // 回到文件开头

    // 逐行读取(方法2:getline)
    while (std::getline(inFile, line)) {
        std::cout << line << std::endl;
    }

    inFile.close();
    return 0;
}

读取二进制数据

#include <fstream>
#include <iostream>

struct Data {
    int id;
    double value;
};

int main() {
    std::ifstream inFile("data.bin", std::ios::binary);
    if (!inFile) {
        std::cerr << "Failed to open binary file!" << std::endl;
        return 1;
    }

    Data data;
    inFile.read(reinterpret_cast<char*>(&data), sizeof(Data));
    std::cout << "ID: " << data.id << ", Value: " << data.value << std::endl;

    inFile.close();
    return 0;
}

二进制文件追加

#include <fstream>
#include <iostream>

struct Data {
    int id;
    double value;
};

int main() {
    // 以二进制追加模式打开文件
    std::ofstream outFile("data.bin", std::ios::binary | std::ios::app);

    if (!outFile) {
        std::cerr << "Failed to open file for appending!" << std::endl;
        return 1;
    }

    // 准备要追加的数据
    Data newData{2, 2.71828};

    // 写入二进制数据(会自动追加到文件末尾)
    outFile.write(reinterpret_cast<char*>(&newData), sizeof(Data));

    outFile.close();
    std::cout << "Data appended to binary file." << std::endl;
    return 0;
}

sstream

从string中读写数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值