C++ 读取文本
介绍三种读取方式:
- 逐字符读取(注意不是字节)
- 读取一行
- 读取全部
示例代码:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream iopen;
iopen.open("/home/lfh/QtProjects/test/main.cpp",ios::in);
int Type = 2; // 1:逐字符, 2:按行读取, 3:读取全部
if ( Type == 1 ) {
cout << "逐字符读取 " << endl;
char a;
while ( iopen.get(a) ) {
cout<<a;
}
}
else if ( Type == 2 ) {
cout << "逐行读取 " << endl;
string str;
while (iopen) {
std::getline(iopen, str);
cout<<str<<endl;
}
}
else if ( Type == 3 ) {
cout << "读取全部 " << endl;
string str;
std::getline(iopen, str, '\0');
cout<<str<<endl;
}
}