我需要读取一个文件,其中包含其他文件的路径,类型以及有关它们的其他数据。 该文件看起来像,
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,无论什么时候我都会得到它的整个路径?
答案 0 :(得分:4)
也许你应该看看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());
}
}
当然,它缺乏各种错误检查。
答案 1 :(得分:1)
如果您只需要提取路径,文件始终如下所示,您可以逐行读取文件并使用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
}
答案 2 :(得分:0)
您要实现的目标实际上是演示如何在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;
}
答案 3 :(得分:0)
如果你想获得当前目录中给定文件的整个路径,下面的代码为你做了,当然使用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;
}