使用c++读取TXT文件中指定行的内容
classification_classes_ILSVRC2012.txt:下载链接
验证:
#include <iostream>
#include <assert.h>
#include <vector>
#include <fstream>
using namespace std;
// 读取txt文件的某一行
int CountLines(string filename)
{
ifstream ReadFile;
int n = 0;
string tmp;
ReadFile.open(filename.c_str());//ios::in 表示以只读的方式读取文件
if (ReadFile.fail())//文件打开失败:返回0
{
return 0;
}
else//文件存在
{
while (getline(ReadFile, tmp, '\n'))
{
n++;
}
ReadFile.close();
return n;
}
}
string ReadLine(string filename, int line)
{
int lines, i = 0;
string temp;
fstream file;
file.open(filename.c_str());
lines = CountLines(filename);
if (line <= 0)
{
return "Error 1: 行数错误,不能为0或负数。";
}
if (file.fail())
{
return "Error 2: 文件不存在。";
}
if (line > lines)
{
return "Error 3: 行数超出文件长度。";
}
while (getline(file, temp) && i < line - 1)
{
i++;
}
file.close();
return temp;
}
int main()
{
加载分类的.txt文件 提取某一行的内容
string filename = "F:\\Pycharm\\PyCharm_Study\\Others\\c++_learning\\C++_Master\\Onnx\\classification\\classification_classes_ILSVRC2012.txt";
int line = 5;
string tmp = ReadLine(filename, line);
cout << tmp << endl;
printf("Done!\n");
system("pause");
return 0;
}
参考:https://blog.csdn.net/weixin_41364297/article/details/98595081