【发布时间】:2014-01-28 06:54:35
【问题描述】:
我有一组数据文件存储在一个目录中。 例如。
./FT/Fourier_1
./FT/Fourier_2
./FT/Fourier_3
...
我的代码最初会生成这些文件的路径列表。
std::string fileStringSearch="Fourier";
std::stringstream resultFileName;
std::vector<std::string> fileList;
int numLines=0;
DIR *parentDirPointer;
struct dirent *dp;
if ((parentDirPointer = opendir("FT")) == NULL)
{
std::cout << "Unable to open the parent (FT) directory" << std::endl;
return(3);
}
while ((dp = readdir(parentDirPointer)) != NULL)
{
std::string testFileName = dp->d_name;
if (testFileName.find(fileStringSearch) != std::string::npos)
{
resultFileName << "FT/" << dp->d_name;
std::string blahblah=resultFileName.str();
fileList.push_back(blahblah);
numLines++;
resultFileName.str(std::string());
resultFileName.clear();
}
};
sort(fileList.begin(),fileList.end());
for (unsigned n=0; n<fileList.size(); ++n)
{
resultFileName << fileList.at(n) << std::endl;
}
FTFilePaths = resultFileName.str();
然后我想从每个文件中读取数据并将其以某种格式存储,以便以后读取、在函数中使用等。
我目前的想法是一个结构 - 我有:
struct Wavenum_struct {
std::string name;
double timestep;
double indexToK_Multiplier;
std::vector<double> Amp_k;
std::vector<double> dFTdt_prev_to_this;
}
稍后在我的程序中,我读取了这些文件,例如:
for (int lineCounter=0; lineCounter < numLines; lineCounter++)
{
getline(readPath, FilePathLine);
c = FilePathLine.c_str();
readFile.open(c);
extern Wavenum_struct c;
c.name = FilePathLine;
//print_name(c);
while(getline (readFile, lineToRead))
{
readFile >> value;
c.Amp_k.push_back(value);
}
//print_amps(c);
}
注释掉的 print_amps(c);可以很好地使用类似的功能:
void print_amps(struct Wavenum_struct t)
{
for(int i=0; i<t.Amp_k.size(); i++)
{
std::cout << i << ": " << t.Amp_k[i] << std::endl;
}
}
但这显然会打印每个结构的振幅,而且只打印一次。如果我想稍后在程序中引用特定的结构,并有选择地打印它们,(或不打印它们,但将它们用于某些功能)例如
void dFTdt(struct Wavenum_struct t_i, struct Wavenum_struct t_i1)
{
int numWavenums = t_i.Amp_k.size();
double dt = t_i1.timestep - t_i.timestep;
double dFTdt[numWavenums];
for (int k=0; k<numWavenums; k++)
{
dFTdt[k] = (t_i1.Amp_k[k] - t_i.Amp_k[k])/dt;
}
t_i1.dFTdt_prev_to_this.assign(dFTdt, dFTdt+numWavenums);
}
然后我似乎无法到达任何地方,因为 c 返回被识别为 for 循环之外的 const * char,以及我尝试过的任何东西:
print_amps(reinterpret_cast<Wavenum_struct*>("FT/Fourier_1"));
拒绝编译。
我假设我需要的可能涉及指向函数的指针和 print_name() 作为结构的函数,但这似乎对我的 void dFTdt() 函数没有帮助,我仍然不知道一旦 c 不再给出该结构的名称,如何引用给定的结构。
这有可能吗?
【问题讨论】:
-
extern Wavenum_struct c;为什么是extern?你也在那里重新声明c。您不需要到处都使用struct关键字(仅在Wavenum_struct的定义中)。为什么不直接使用vector<Wavenum_struct>来存储所有文件数据?我根本不明白这与类型名称有什么关系。 -
啊,这是后来努力使结构的名称可以引用 - 最初没有
extern。至于重新声明c,我怀疑这就是我的问题所在,因为以后不可能(我认为?)再参考它。我将从(struct Wavenum_struct t)等中删除struct- 谢谢。对于“为什么不使用vector<Wavenum_struct>来存储所有文件数据”,您的意思是以某种方式而不是readFile >> value; c.Amp_k.push_back(value);部分? -
@Beta 在下面的答案中概述了
vector<Wavenum_struct>的使用。