c++ - 以下递归目录搜索和文件打开有什么问题?

标签 c++ c fwrite fread dirent.h

我正在尝试访问一个目录中的所有文件,并对这个目录和后续目录下的文件做一些事情。对于此操作,我在 Windows 中使用了 dirent.h,它设法获取所有文件并打开和关闭这些文件。我的问题是,当我尝试从它们中读取一些内容并写入另一个内容时,如下所示,我得到了最后显示的错误。

代码如下:

#include <iostream>
#include <cstring>
#include <sys/stat.h>
#include <dirent.h>
FILE *test_file;
char buffer[51];
void listdir(const char *path) 
{
  struct dirent *entry;
  DIR *dp;

  //std::cout << "Dir: " << path << "\n";

  if(dp = opendir(path))
  {
    struct stat buf ;
    FILE *input_file;

    while((entry = readdir(dp)))
    {
        std::string p(path);
        p += "\\";
        p += entry->d_name;
        char fpath[250];
        //strcpy(fpath,path);
        if(!stat(p.c_str(), &buf))
        {
            if(S_ISREG(buf.st_mode))
            {
                std::cout << "    File: " << entry->d_name << "\n";
                sprintf(fpath,"%s\\%s",path,entry->d_name);
                input_file=fopen(fpath,"r+b");
                test_file=fopen("test_test.txt","a+b");
                if(input_file==NULL)
                {
                std::cout<<"\n Could not open\n"<<entry->d_name<<std::endl;
                continue;
                }
                if(test_file==NULL)
                    goto z;
                else 
                {
                    std::cout<<"\n Successfully Opened\n"<<fpath;
                    fread(buffer,50,1,input_file);
                    fprintf(test_file,"\n\n%s\n\n",fpath);
                    fwrite(buffer,50,1,test_file);

                    fclose(input_file);
                     fclose(test_file);
                    // free(buffer);
                }
z:
                if(test_file=NULL)
                fclose(test_file);
            }
            if(S_ISDIR(buf.st_mode) &&  
         // the following is to ensure we do not dive into directories "." and ".."
                      strcmp(entry->d_name, ".")  && strcmp(entry->d_name, "..") )
            {
                listdir(p.c_str());
            }
        }
        else
            std::cout << "ERROR in stat\n";
    }
   // delete buf;
    closedir(dp);
  }
  else
    std::cout << "ERROR in opendir\n";
  fclose(test_file);
}

int main(int argc, char **argv) 
{
  listdir(argv[1]);
  return 0;
}

它设法打开并读取第一个文件,但在第一个文件之后它将显示以下错误并打开 dbgheap.c

HEAP[direntdir.exe]: Invalid address specified to RtlValidateHeap( 002C0000, 002C5718 ) Windows has triggered a breakpoint in direntdir.exe.

This may be due to a corruption of the heap, which indicates a bug in direntdir.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while direntdir.exe has focus.

The output window may have more diagnostic information.

编辑: 更正了 buf 变量的错误。

现在我明白了

Debug Assertion Failed!

... Expression:(buffer!=NULL) ...

最佳答案

你有两个名为 buf 的变量:

char* buf;
...
struct stat *buf = new struct stat;

后者隐藏了第一个,而后者是 free()d,即使它是使用 new 创建的,然后在没有重新分配的情况下被重用。 后者也用作 fread() 的参数。重命名 char* buf 并可能使其成为函数的本地并且只使用堆栈分配的缓冲区:

char fread_buffer[51];

编辑:

char* bufferfread() 中使用之前从未为其分配内存,因此对 fread() 的调用可能正在写入内存中的任何地方。更改为:

char buffer[50]; /* as only 50 bytes are read from the file */

并且如果 buffer 是以这种方式声明的,则不要调用 free()

此外,为了简化事情,只需将 buf 声明为:

struct stat buf;

并调用stat():

if(!stat(p.c_str(), &buf))

进行这两项更改将从代码中删除所有动态内存管理。

编辑 2:

这个 if 是一个赋值,而不是一个不等式检查:

if(test_file=NULL)
    fclose(test_file);

应该是:

if(NULL != test_file)
    fclose(test_file);

关于c++ - 以下递归目录搜索和文件打开有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547885/

相关文章:

c++ - 基于指针的链表给出段错误

c++ - 将宏设置为值,如果为空

c++ - 如何将txt文件中的多个值输入数组C++

c - 如何正确使用函数?

c - 如何在 C 中使用 ncurses 获取屏幕位置的字符?

c - 在c中将ByteArray写入文件

c++ - 获取 std::string 字符串的大小(以字节为单位)

c - 零大小 malloc

c++ - C/C++ 将多个字节发送到标准输出的最佳方法

php - 如何在表单中的每个输入/新行之后添加 <br/> 标签