C++自定义读取函数为文件夹中的前两个文件返回错误的值
C++ custom read function return wrong values for the first two files inside a folder
所以我的问题是,我有一个文件夹,里面有".dat"文件,其中包含计算光谱的数值。每个数据文件都有一组行和列。
使用此代码,对于函数打开的前两个文件,我得到了错误的数据文件中的行数值。
这是我的代码
#include <algorithm>
#include <fstream>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string.h>
#include <iostream>
using namespace std;
int getdir(string, vector<string>&);
int getsize(vector<string>&, vector<int>&);
int main(){
string dir = string("input");
vector<string> files = vector<string>();
vector<int> filesize = vector<int>();
getdir(dir,files);
getsize(files, filesize);
return 0;
}
int getdir (string path, vector<string> &files){
DIR *dir;
struct dirent *entry;
if((dir = opendir(path.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << path << endl;
return errno;
}
while((entry = readdir(dir)) != NULL) {
if(strcmp(entry->d_name, "." ) == 0 || strcmp(entry->d_name, ".." ) == 0 ){
continue;
}
//cout<<entry->d_name<<endl;
files.push_back(string(entry->d_name));
}
closedir(dir);
return 0;
}
int getsize(vector<string> &filename, vector<int> &filesize){
ifstream *read = new ifstream[filename.size()];
string *f = new string[filename.size()];
string *line = new string[filename.size()];
int *numlines = new int[filename.size()];
sort(filename.begin(), filename.end());
for(unsigned int i=0; i<filename.size(); i++){
f[i] = "input/"+filename[i];
read[i].open(f[i].c_str(), ios::in);
cout<<"File["<<i<<"] "<<filename[i]<<endl;
while(read[i].good()){
getline(read[i], line[i]);
++numlines[i];
}
filesize.push_back(numlines[i]);
cout<<filesize[i]<<endl;
read[i].close();
}
delete[] f;
delete[] line;
delete[] read;
delete[] numlines;
}
无法上传图像,我的结果如下:
File[0] filename1.dat
5518348
File[1] filename2.dat
5510484
File[2] filename3.dat
108
File[3] filename4.dat
108
.
.
有什么建议我可以做些什么来获得正确的读数吗?感谢您的帮助和反馈。
祝你好运。
在行中:
int *numlines = new int[filename.size()];
您从不初始化这些值,所以它们一开始就是垃圾。为了解释您的结果,可能发生的情况是前两个条目具有较大的垃圾值,而后面的条目偶然具有0
。
要解决这个问题,你可以写:
int *numlines = new int[filename.size()]();
也可以在使用之前将numlines[i]
设置为0
然而,我强烈考虑去掉所有这些数组(这太疯狂了,TBH(。只需在i
循环中声明每件事中的一件。
相关文章:
- 两个文件使用彼此的功能-如何解决
- 结构包含在两个头文件中,这两个文件我都不拥有
- Levenshtein 两个文件的距离花费了太多时间
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 包括两个文件 C++ 之间的冲突
- 如何检测两个文件条目是否引用与Qt相同的物理文件系统?
- 比较两个文件夹的关系
- 连接两个文件时如何避免冗余尾随换行符?
- 在循环工作时,首先将两个文件读为向量,但仅次于迭代一次
- 比较两个文件中的两个中间人的最佳方法.C++
- 同时逐行阅读两个文件
- 包含两个C++文件的制作文件:如何选择要编译的文件
- 在 c++ 中对两个文件使用标头
- 同时阅读两个文件
- 如何连接两个文件夹/项目的生成文件,这两个文件夹/项目必须一起运行且独立运行
- 从其他两个文件中创建一个分类整数的文件
- C 程序处理两个文件,而不是一个文件
- 知道分割故障在哪里比较两个文件
- 如何计算两个文件中字符单词和行的总数,并将它们相加以得出总数
- 将相同数据写入两个文件的有效方法