依赖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
网友评论