C++ 标准输入输出(stdin/stdout)

C++ 中使用 std::cinstd::cout 处理标准输入输出。std::cin 从标准输入(stdin)读取数据,std::cout 向标准输出(stdout)写入数据。

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "You entered: " << num << endl;
    return 0;
}

C++ 文件读写(fstream)

使用 <fstream> 库进行文件操作,主要类包括:

  • ifstream:输入文件流(读取文件)
  • ofstream:输出文件流(写入文件)
  • fstream:通用文件流(读写文件)
写入文件(ofstream)
#include <fstream>
using namespace std;

int main() {
    ofstream outFile("example.txt");
    if (outFile.is_open()) {
        outFile << "Hello, File!\n";
        outFile << 42 << endl;
        outFile.close();
    }
    return 0;
}

读取文件(ifstream)
#include <fstream>
#include <iostream>
using namespace std;

int main() {
    ifstream inFile("example.txt");
    string line;
    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    }
    return 0;
}

二进制文件读写

对于非文本数据(如图片、音频),需使用二进制模式:

#include <fstream>
using namespace std;

int main() {
    // 二进制写入
    ofstream binOut("data.bin", ios::binary);
    int data = 12345;
    binOut.write(reinterpret_cast<char*>(&data), sizeof(data));
    binOut.close();

    // 二进制读取
    ifstream binIn("data.bin", ios::binary);
    int readData;
    binIn.read(reinterpret_cast<char*>(&readData), sizeof(readData));
    cout << "Read: " << readData << endl;
    binIn.close();

    return 0;
}

文件状态检查

文件操作时应检查状态:

  • is_open():检查文件是否成功打开
  • good():检查流状态是否正常
  • fail():检查是否发生非致命错误
  • eof():检查是否到达文件末尾
ifstream file("data.txt");
if (!file) {
    cerr << "Error opening file" << endl;
    return 1;
}

文件定位

使用 seekg()tellg() 控制读取位置:

ifstream file("data.txt");
file.seekg(0, ios::end); // 移动到文件末尾
streampos size = file.tellg();
file.seekg(0, ios::beg); // 回到文件开头

综合示例:文件拷贝

#include <fstream>
using namespace std;

int main() {
    ifstream src("source.txt", ios::binary);
    ofstream dst("destination.txt", ios::binary);

    dst << src.rdbuf(); // 高效拷贝整个文件

    src.close();
    dst.close();
    return 0;
}

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐