I fairly new to C++. I have to write a C++ program that will display the contents of a folder and if the item is a file it has to show the file size. I cant get the file size to work, here is what I have so far.
void FileList()
{
DIR * dir;
dirent * pdir;
struct stat * pfile;
dir = opendir(".");
while(pdir = readdir(dir))
{
switch (pdir->d_type)
{
case DT_REG:
// Regular file
cout<<pdir->d_name<<pfile->st_size<<endl;
break;
case DT_DIR:
// Directory
cout<<pdir->d_name<<"<DIR>"<<endl;
break;
default:
// Unhandled by this example
cout<<"Is nothing"<<endl;
}
You did not call stat() anywhere in your code. Call it first.
1 2 3 4 5 6 7
switch (pdir->d_type)
{
case DT_REG:
// Regular file
stat (pdir->d_name, pfile);
cout<<pdir->d_name<<pfile->st_size<<endl;
break;
Also I don't really understand if stat() allocated the struct itself or just expect one from the programmer (in this last case your program will crash)