美文网首页
C++ 文件解析

C++ 文件解析

作者: sudocloud | 来源:发表于2019-11-18 15:42 被阅读0次

    依赖gcc、 cmake

    1. 代码编写

    main.cpp

    #include <iostream>
    #include <fstream>
    #include <vector>
    
    using namespace std;
    
    const static string fileName = "data.txt";
    
    int save()
    {
        fstream file(fileName, ios::out);
        if (!file.is_open()) 
        {
            cout << "open file " << fileName << " fail." << endl;
            return -1;
        }
        
        for (int i=0; i<10; i++)
        {
            file <<"line:" << i<< " Hello world!" << endl;
        }
    
        file.close();
        return 0;
    }
    
    int load(vector<string>& data)
    {
        fstream file(fileName, ios::in);
        if (!file.is_open()) 
        {
            cout << "open file " << fileName << " fail." << endl;
            return -1;
        }
        while(!file.eof())
        {
            string strLine;
            getline(file, strLine);
            data.push_back(strLine);
        }
    
        file.close();
        return 0;
    }
    
    int main()
    {
        vector<string> data;
        data.clear();
    
        save();
        load(data);
    
        for (int i = 0; i < data.size(); i++)
        {
            cout << data[i] << endl;
        }
    
        return 0;
    }
    

    2. cmake 编写

    CMakeLists.txt

    
    

    相关文章

      网友评论

          本文标题:C++ 文件解析

          本文链接:https://www.haomeiwen.com/subject/hmlbictx.html