【发布时间】:2016-04-03 20:54:01
【问题描述】:
我有一个包含 15 个文件夹的目录,每个文件夹有 100 个文本文件。在每个文本文件中都包含一列数字。
我需要这些数字来做一些计算,但我不知道如何获得它。我在考虑一个二维向量,但我需要不同类型的数据结构(文件夹名称的字符串和数字的整数)。
我最好的解决方案是什么?d
到目前为止,我得到的是一个代码,它将通过给定的路径搜索所有文件。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <tuple>
#include <boost/filesystem.hpp>
#include<dirent.h>
using namespace std;
namespace fs = boost::filesyst
// prototype to search all the files by given it a path
vector<double> getFilesFromDirectory(const fs::path& startDirectory);
int main()
{ // the directory
string dir = "/home/...";
// testing to call my methode
vector<double> myDataStructure = getFilesFromDirectory(dir);
// print out the value of myDataStructure
for (auto it = myDataStructure.begin(); it != myDataStructure.end(); it++)
{
cout << *it << " " << endl;
}
return 0;
}
// methode to search all the files by given it a path
vector<double> getFilesFromDirectory(const fs::path& startDirectory)
{
vector<double> di;
// First check if the start path exists
if (!fs::exists(startDirectory) || !fs::is_directory(startDirectory))
{
cout << "Given path not a directory or does not exist" << endl;
exit(1);
}
// Create iterators for iterating all entries in the directory
fs::recursive_directory_iterator it(startDirectory); // Directory iterator at the start of the directory
fs::recursive_directory_iterator end; // Directory iterator by default at the end
// Iterate all entries in the directory and sub directories
while (it != end)
{
// Print leading spaces
for (int i = 0; i < it.level(); i++)
cout << "";
// Check if the directory entry is an directory
// When directory, print directory name.
// Else print just the file name.
if (fs::is_directory(it->status()))
{
// print out the path file
cout << it->path() << endl;
}
else
{
cout << it->path().filename() << endl;
// test
di = getValueFromFile(it->path().c_str());
// test, here I want to group the numbers of the file
// and each name of the folder
for(int i = 0; i < 15; i++)
{
di.push_back(mi(fs::basename(it->path()), it->path().c_str());
}
}
// When a symbolic link, don't iterate it. Can cause infinite loop.
if (fs::is_symlink(it->status()))
it.no_push();
// Next directory entry
it++;
}
return di;
}
【问题讨论】:
-
文件是否以某种方式相互关联,或者是独立的?这是一种转变,还是某种减少?如果它是您感兴趣的每个文件的单个值,并且您为每个文件报告这些结果,为什么不直接使用
std::vector<std::tuple<boost::filesystem::path, ValueType>>其中 ValueType 是您在计算中使用的任何类型? -
文件与文件夹相互关联。我的想法是在获得每个文件夹的每个数字后在 Excel 中制作图表。嗯,也许这可以工作。我会看看。谢谢
-
是的,很抱歉我没有显示所有代码。此代码将文本文件转换为双精度文件。 getValueFromFile 方法就是这样做的。
标签: c++ data-structures directory iteration boost-filesystem