How to perform file operations in C++?

In C++, including header files is typically necessary for file operations. Here are some commonly used file operation functions:

  1. Open the file:
#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. Read the content of the file.
#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. Write the contents to the file.
#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. Seek to a specified position in the file for reading and writing.
#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;
}

These are commonly used file operation functions in C++, which can be called based on specific needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds