私はディレクトリ内のすべてのファイルにアクセスしようとしており、このディレクトリとそれに続くディレクトリの下にあるファイルについて何らかの作業を行っています。この操作では、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]:無効なアドレスがRtlValidateHeapに指定されています( 002C0000,002C5718) direntdir.exeにブレークポイントがトリガーされました。
これは、 direntdir.exeまたはそれがロードしたいずれかのDLLのバグを示す、ヒープが破損している可能性があります。
これは、direntdir.exeのフォーカスが である間にユーザーがF12キーを押したことが原因である可能性もあります。
出力ウィンドウには、より多くの診断情報が含まれている場合があります。
EDIT: は bufの変数でエラーを修正しました。
は、今私は
デバッグアサートに失敗しました得ます!
...式:(!バッファ= NULL)...
あなたが両方の解放と 'buf'を削除している(これはそれ自体は非常に疑わしい)とAFAICTは、どこにでもストレージを割り当てない(初期化していない)。 (CスタイルのコードとC++の混在はかなり混乱しています) – Mat