Bootstrap

c++读写文本文件

写在前面

1、本文内容
c++读写文件
2、转载请注明出处:
https://blog.csdn.net/qq_41102371/article/details/125929650

代码

#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[]){
    //写文件
    std::ofstream file_out;
    file_out.open("./data.txt");
    if(!file_out.is_open()){
        std::cout<<"open file failed!"<<std::endl;
    }
    file_out<<"1\n2"<<std::endl;
    file_out.close();


    std::ifstream file_in;
    file_in.open("./data.txt",std::ios::app);
        if(!file_in.is_open()){
        std::cout<<"open file failed!"<<std::endl;
    }
    //读文件
    std::string str;
    while(getline(file_in,str)){
        std::cout<<str<<std::endl;
    }
    file_in.close();
    return 0;
}

reference

https://zh.cppreference.com/w/cpp/io/basic_ofstream/open
【C++】读取 .txt 文件中的一列或多列数据(非常实用) https://blog.csdn.net/weixin_47156401/article/details/121798931

;