mcuw mcuw - 7 days ago 5
C++ Question

How can I get the file size in directory traversal?

Using qt and C++ how can I get the size of a file when I am using recursion to look at each file? (I've get error: project.exe exited with code -1073741819)

int dir_size(const QString str)
{
long int sizex = 0;
QFileInfo str_info(str);
if (str_info.isDir())
{
QDir dir(str);
QStringList ext_list;
dir.setFilter(QDir::Files | QDir::Dirs | QDir::Hidden | QDir::NoSymLinks);
QFileInfoList list = dir.entryInfoList();

for(int i = 0; i < list.size(); ++i)
{
QFileInfo fileInfo = list.at(i);
if ((fileInfo.fileName() != ".") && (fileInfo.fileName() != ".."))
{
if(fileInfo.isDir())
{
sizex += this->dir_size(fileInfo.path());
QApplication::processEvents();
}
else
{
sizex += fileInfo.size();
QApplication::processEvents();
}
}
} // for
} // if

return sizex;
}

Answer

Its crashing because you are recursively evaluating the same folder again and again. The statement sizex += this->dir_size(fileInfo.path()); calls the same function recursively with the same folder name. So your stack keeps growing and eventually out of memory.

fileInfo.path() gives the same (parent) folder.

fileInfo.filePath() gives the filename with the path

Change it to sizex += this->dir_size(fileInfo.filePath()); and that should fix it