我有一个名为myfile.txt
的文本文件,它列出了驱动器D:\
的内容。在我的程序中,我有一个函数,它将读取myfile.txt
。它将从.txt
扩展中提取文件名。我不太了解C++,所以你可以让它“简单”吗?我对子字符串的起始位置感到困惑,因为我将如何知道它将从何处开始。如何从文本文件中提取带.txt扩展名的文件名?
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(void)
{
system("cls");
string temp;
fstream file;
file.open("D:\\myfile.txt", ios::in);
while(file.good())
{
file>>temp;
string str2, str3;
size_t pos;
str2 = temp.substr (4,4); // confused with this
pos = temp.find(".txt"); // position of ".txt" in temp
str3 = temp.substr (pos);
cout << str2 << ' ' << str3 << endl;
}
system("pause");
return 0;
}
另一点 - 如果你在unix系统上,你甚至可以在你进入你的程序之前做过滤。即'find/-type f -iname'* .txt“> textFiles.txt' – I82Much 2011-04-07 18:40:47
或者,如果你已经有了'grep'txt $'< files.txt > textfiles.txt'的列表。 – 2011-04-07 18:59:34