如何从文本文件中提取带.txt扩展名的文件名?
问题描述:
我有一个名为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;
}
答
- 加载文件,从中提取所有线(在可变名单店)(http://www.linuxquestions.org/questions/programming-9/c-text-file-line-by-line-each-line-to-string-array-126337/)
- 遍历目录,并删除所有不与.TXT(Find if string ends with another string in C++)
+1
如果只有.001%的文件名以“.TXT”结尾,那么这看起来像是浪费了内存。怎么样'std :: istream_iterator'而不是创建第一个列表? – 2011-04-07 17:52:02
+0
我同意这不是最有效的方法。然而,它可能是最简单的概念,我希望OP得到一个工作实现,并担心后来改进它,而不是担心过早地优化它。 – I82Much 2011-04-07 18:39:26
答
#include <fstream>
#include <vector>
#include <string>
int main (int argc, char* argv[])
{
if (argc != 2)
return 1;
std::ifstream file(argv[1]);
if (!file.is_open())
return 2;
std::vector<std::string> files;
std::string line;
while (std::getline(file, line)) {
if(line.length() < 4)
continue;
if(line.substr(line.length() - 4, std::string::npos) == ".txt")
files.push_back(line);
}
/* all files ending with .txt are in "files" */
return 0;
}
结束串
答
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
// inspried by http://www.cplusplus.com/reference/std/iterator/istream_iterator/
struct getline :
public std::iterator<std::input_iterator_tag, std::string>
{
std::istream* in;
std::string line;
getline(std::istream& in) : in(&in) {
++*this;
}
getline() : in(0) {
}
getline& operator++() {
if(in && !std::getline(*in, line)) in = 0;
}
std::string operator*() const {
return line;
}
bool operator!=(const getline& rhs) const {
return !in != !rhs.in;
}
};
bool doesnt_end_in_txt(const std::string& s) {
if (s.size() < 4)
return true;
if (s.compare(s.size()-4, 4, ".txt") != 0)
return true;
}
int main() {
std::vector<std::string> v;
std::remove_copy_if(getline(std::cin), getline(),
std::back_inserter(v),
doesnt_end_in_txt);
}
另一点 - 如果你在unix系统上,你甚至可以在你进入你的程序之前做过滤。即'find/-type f -iname'* .txt“> textFiles.txt' – I82Much 2011-04-07 18:40:47
或者,如果你已经有了'grep'txt $' textfiles.txt'的列表。 – 2011-04-07 18:59:34