[C++] 파일 한줄씩 읽기 두가지 함수
/*
파일 한줄씩 읽기 두가지 함수
*/
#include <iostream>
#include <string>
#include <string.h>
#include <vector>
#include <fstream>
#include <stdio.h>
using namespace std;
vector<string> ReadAllLines1(string sPath);
vector<string> ReadAllLines2(string sPath);
int main()
{
cout << "ReadAllLines1------------------"<< endl;
vector<string> vec1;
vec1 = ReadAllLines1 ("Sum.cpp");
for(auto s:vec1)
{
cout << s << endl;
}
cout << "ReadAllLines2------------------"<< endl;
vector<string> vec2;
vec2 = ReadAllLines2 ("Sum.cpp");
for(auto s:vec2)
{
cout << s << endl;
}
return 0;
}
vector<string> ReadAllLines1(string sPath)
{
vector<string> vRet;
FILE *fp = fopen(sPath.c_str(), "r");
if (NULL != fp)
{
char buf[512];
char *ps;
while (NULL != fgets(buf, sizeof(buf), fp))
{
ps = strchr(buf, '\n');
if (ps != NULL) *ps = '\0';
vRet.push_back(string(buf));
}
fclose(fp);
}
return vRet;
}
vector<string> ReadAllLines2(string sPath)
{
vector<string> vRet;
string sLine("");
ifstream in(sPath.c_str());
if (in.is_open())
{
while(!in.eof())
{
getline(in, sLine);
vRet.push_back(sLine);
}
in.close();
}
return vRet;
}