我需要读取一个文件,其中包含其他文件的路径、类型和有关它们的其他数据。 该文件看起来像,
LIST OF SUB DIRECTORIES:
Advanced System Optimizer 3
ashar wedding and home pics
components
Documents and Settings
khurram bhai
media
new songs
Office10
Osama
Program Files
RECYCLER
res
Stationery
System Volume Information
Templates
WINDOWS
LIST OF FILES:
.docx 74421
b.com 135168
ChromeSetup.exe 567648
Full & final.CPP 25884
hgfhfh.jpg 8837
hiberfil.sys 267964416
myfile.txt.txt 0
pagefile.sys 402653184
Shortcut to 3? Floppy (A).lnk 129
Thumbs.db 9216
vcsetup.exe 2728440
wlsetup-web.exe 1247056
我只需要提取文件的路径名并将它们保存在一个数组中,但我坚持使用它。这是我的代码,
// read a file into memory
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int length;
char str[600];
ifstream is;
is.open ("test.txt", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// read data as a block:
is.read (str,length);
//**find the path of txt files in the file and save it in an array...Stuck here**
is.close();
return 0;
}
我很困惑下一步该怎么做。即使我使用 strstr() 来查找 .txt,我如何获得它的完整路径?
最佳答案
也许你应该看看boost filesystem library .
它提供你需要的东西。
这应该是它如何工作的一个例子。虽然我没有尝试,但它应该可以编译。
boost::filesystem::path p("test.txt");
boost::filesystem::path absolutePath = boost::filesystem::system_complete(p);
boost::filesystem::path workDir = absolutePath.parent_path();
std::vector<std::string> file;
std::string line;
std::ifstream infile ("test.txt", std::ios_base::in);
while (getline(infile, line, '\n'))
{
file.push_back (line.substr(0, line.find_first_of(" ")));
}
std::vector<std::wstring> fullFileNames;
for(std::vector<std::string>::const_iterator iter = file.begin(); iter != file.end(); ++iter)
{
boost::filesystem::path newpath= workDir / boost::filesystem::path(*iter);
if(!boost::filesystem::is_directory(newpath) && boost::filesystem::exists(newpath))
{
fullFileNames.push_back(newpath.native().c_str());
}
}
当然,它缺少各种错误检查。
关于c++ - 如何从文件中提取路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5537950/