温馨提示×

C++中怎么进行文件操作

c++
小亿
84
2024-03-11 14:30:29
栏目: 编程语言

在C++中进行文件操作通常需要包含头文件。以下是一些常用的文件操作函数:

  1. 打开文件:
#include <fstream>
#include <iostream>

int main() {
    std::ifstream file("input.txt"); // 打开一个文件用于读取
    //std::ofstream file("output.txt"); // 打开一个文件用于写入
    //std::fstream file("file.txt"); // 打开一个文件用于读写

    if(file.is_open()) {
        std::cout << "文件打开成功" << std::endl;
    } else {
        std::cout << "文件打开失败" << std::endl;
    }

    file.close(); // 关闭文件
    return 0;
}
  1. 读取文件内容:
#include <fstream>
#include <iostream>

int main() {
    std::ifstream file("input.txt");

    if(file.is_open()) {
        std::string line;
        while(std::getline(file, line)) {
            std::cout << line << std::endl;
        }
    } else {
        std::cout << "文件打开失败" << std::endl;
    }

    file.close();
    return 0;
}
  1. 写入文件内容:
#include <fstream>
#include <iostream>

int main() {
    std::ofstream file("output.txt");

    if(file.is_open()) {
        file << "Hello, World!" << std::endl;
    } else {
        std::cout << "文件打开失败" << std::endl;
    }

    file.close();
    return 0;
}
  1. 定位到文件指定位置进行读写:
#include <fstream>
#include <iostream>

int main() {
    std::fstream file("file.txt");

    if(file.is_open()) {
        file.seekp(5); // 将写入位置定位到第5个字符
        file << "Hello";
        
        file.seekg(0); // 将读取位置定位到开头
        std::string content;
        file >> content;
        std::cout << content << std::endl;
    } else {
        std::cout << "文件打开失败" << std::endl;
    }

    file.close();
    return 0;
}

这些是C++中常用的文件操作函数,可以根据具体需求进行调用。

0