美文网首页
C++ 文件读写操作

C++ 文件读写操作

作者: sudocloud | 来源:发表于2019-11-18 14:44 被阅读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

    project(test)
    
    cmake_minimum_required(VERSION 2.8)
    set(CMAKE_CXX_STANDARD 11)
    set(CMAKE_BUILD_TYPE "Debug")
    
    include_directories(
        ${PROJECT_SOURCE_DIR})
    
    aux_source_directory(./ SRC_LIST)
    
    add_executable(${PROJECT_NAME} ${SRC_LIST})
    target_link_libraries(${PROJECT_NAME}
        -ldl -lm -lpthread -lrt)
    
    

    3. 测试运行

    cd test
    mkdir build
    cd build
    cmake ..
    make
    ./test
    

    相关文章

      网友评论

          本文标题:C++ 文件读写操作

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