C++自定义读取函数为文件夹中的前两个文件返回错误的值

C++ custom read function return wrong values for the first two files inside a folder

本文关键字:两个 文件 错误 返回 函数 读取 自定义 文件夹 C++      更新时间:2023-10-16

所以我的问题是,我有一个文件夹,里面有".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循环中声明每件事中的一件。