C++ 从文件中读取行而不存储任何内容会浪费内存

C++ 从文件中读取行而不存储任何内容会浪费内存,c++,memory,memory-leaks,C++,Memory,Memory Leaks,我有一个文件夹,里面有2000个文件夹(0001到2000),每个文件夹都包含许多文件,原始文件夹中总共有145000个文件。 我先读取每个文件夹,然后读取文件夹中的每个文件。对于每个文件,我逐行读取,并进行一些存储和处理。但是内存使用非常糟糕。我认为问题在于存储,但当我清理代码(存储和处理)时,我发现即使没有存储某些东西,内存使用情况也与以前一样。我的文件的总大小为3.6 GB。对一半文件夹(约1.8GB)执行代码后,需要5GB的主内存。这个代码有什么问题? 代码如下: #define LI

我有一个文件夹,里面有2000个文件夹(0001到2000),每个文件夹都包含许多文件,原始文件夹中总共有145000个文件。 我先读取每个文件夹,然后读取文件夹中的每个文件。对于每个文件,我逐行读取,并进行一些存储和处理。但是内存使用非常糟糕。我认为问题在于存储,但当我清理代码(存储和处理)时,我发现即使没有存储某些东西,内存使用情况也与以前一样。我的文件的总大小为3.6 GB。对一半文件夹(约1.8GB)执行代码后,需要5GB的主内存。这个代码有什么问题? 代码如下:

#define  LINE_BUFFER_LEN        40960
int main(int argc, char** argv) {
    DIR *dpdf;
    struct dirent *epdf;
    string fcount;
    string path="/media/modb/78E60A4AE60A0958/final/"; 
    string filename, filenumber;
    int filenum;
    char buffer[LINE_BUFFER_LEN];
    string readFilePath;
    ifstream infile;

    int folderCount=1;
    int periodFilesCount=0;
    while (folderCount<2001){
        fcount=IntToString(folderCount);
        numOfzeros=(4-fcount.size());
        fcount.insert(fcount.begin(), numOfzeros, '0');
        dpdf = opendir((path+fcount).c_str());
        if (dpdf != NULL){
           while (epdf = readdir(dpdf)){
               if (epdf->d_type==8){
                    filename=string(epdf->d_name);
                    filename=(filename.substr(0,filename.size()-4));

                    filenumber=(filename.substr(filename.find('_')+1,filename.size()));
                    filenum=atoi(filenumber.c_str());

                    readFilePath=path+fcount+"/"+filename+".txt";
                    infile.open(readFilePath.c_str());

                    if(!infile) {
                            cout<<"Error\n";
                    }
                    while(infile.getline(buffer, LINE_BUFFER_LEN))
                    {
                        //The code cleaned from here.
                        loopCounter++;
                    }
                    infile.close();
                    cout<<endl;
               }
           }
        }
        closedir(dpdf);
        folderCount++;
    }
    return 0;
}
#定义行_BUFFER_LEN 40960
int main(int argc,字符**argv){
DIR*dpdf;
结构方向*epdf;
字符串fcount;
字符串路径=“/media/modb/78E60A4AE60A0958/final/”;
字符串文件名,文件号;
int filenum;
字符缓冲区[LINE_buffer_LEN];
字符串读取文件路径;
河流充填;
int folderCount=1;
整数周期文件计数=0;
while(folderCountd_type==8){
文件名=字符串(epdf->d_名称);
filename=(filename.substr(0,filename.size()-4));
filenumber=(filename.substr(filename.find(“”“)+1,filename.size());
filenum=atoi(filenumber.c_str());
readFilePath=path+fcount+“/”+filename+“.txt”;
open(readFilePath.c_str());
如果(!infle){

你在测量内存使用情况吗?在使用free-m的Linux中。也就是说,对于整个文件,它会因分段错误而失败。因此,基本上你是在抱怨Linux使用的是“free”缓存文件的内存…我建议您使用
ps
top
/proc/[pid]/status
的内容来衡量程序的内存使用情况。好的!明白了。谢谢您的评论。