C++读取txt文件的时候可以使用std::ifstream来实现,如果打开文件失败的话,其变量会是空的,所以可以用来判断是否打开成功。
#include <stdlib.h>
#include <fstream>
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::ifstream fIn("str.txt");
if (fIn)
{
std::string str;
while (std::getline(fIn, str))
{
std::cout << str << std::endl;
}
}
else
{
std::cout << "Open file faild." << std::endl;
}
fIn.close();
system("pause");
return 0;
}
运行的结果如下:
懒拂鸳鸯枕,
休缝翡翠裙,
罗帐罢炉熏。
近来心更切,
为思君。