C++文件寫入與讀取

在寫項目時,往往需要配置一些數據,這裏做個記錄

#include <fstream>      //ifstream讀文件,ofstream寫文件,fstream讀寫文件
#include <string>
#include <iostream>
using namespace std;
 
int main()
{
    ifstream in("../data/讀取.txt");
    string line;

    if(in) // 判斷時候有該文件
    {
        while (getline (in, line)) // line中不包括每行的換行符
        {
            int ind = line.find(':');
            string str = line.substr(ind+1);
            cout << str << endl;
        }
    }
    else // 沒有該文件
    {
        cout <<"讀取文件打開失敗" << endl;
    }

    ofstream out("../data/寫入.txt");
    if(out) // 判斷是否有該文件
    {
        out << "寫入成功" << endl;
        out << "寫入完成" << endl;
    }
    else // 沒有該文件
    {
        cout <<"寫入文件打開失敗" << endl;
    }

    in.close();
    out.close();

    return 0;

}


文件鏈接:https://download.csdn.net/download/OEMT_301/12331584

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章