我需要读取一个文件,其中包含其他文件的路径,有类型和其他数据。文件看起来像这样,
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文件系统库。
它提供了你需要的东西。
这应该是一个如何工作的例子。虽然我没有试过,但它应该可以编译。
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());
}
}
当然,它缺少各种错误检查
如果您只需要提取路径,并且文件总是看起来像这样,您可以逐行读取文件并使用string::find
查找空格的第一次出现,并为每个条目创建一个子字符串。
size_t index = str.find(" ");
if(index != string::npos) // sanity checing
{
string path = str.substr(0, index);
//do whatever you want to do with the file path
}
您想要完成的实际上是演示如何在cplusplus.com上使用string::find_last_of
的示例代码:
void SplitFilename (const string& str)
{
size_t found;
cout << "Splitting: " << str << endl;
found=str.find_last_of("/\");
cout << " folder: " << str.substr(0,found) << endl;
cout << " file: " << str.substr(found+1) << endl;
}
如果您想获得当前目录中给定文件的整个路径,下面的代码可以帮您完成,当然使用boost:
#include <iostream>
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main()
{
fs::path my_path("test.txt");
if(fs::is_regular_file(my_path)) // Sanity check: the file exists and is a file (not a directory)
{
fs::path wholePath = fs::absolute(my_path);
std::cout << wholePath.string() << std::endl;
}
return 0;
}