C++ stat.h incomplete type and cannot be defined

user788171 picture user788171 · Feb 14, 2012 · Viewed 10.1k times · Source

I am having a very strange issue with stat.h

At the top of my code, I have declarations:

#include <sys\types.h> 
#include <sys\stat.h> 

And function prototype:

int FileSize(string szFileName);

Finally, the function itself is defined as follows:

int FileSize(string szFileName)
{
  struct stat fileStat; 
  int err = stat( szFileName.c_str(), &fileStat ); 
  if (0 != err) return 0; 
  return fileStat.st_size;
}

When I attempt to compile this code, I get the error:

divide.cpp: In function 'int FileSize(std::string)':
divide.cpp:216: error: aggregate 'stat fileStat' has incomplete type and cannot be defined
divide.cpp:217: error: invalid use of incomplete type 'struct stat'
divide.cpp:216: error: forward declaration of 'struct stat'

From this thread: How can I get a file's size in C? I think this code should work and I cannot figure out why it does not compile. Can anybody spot what I am doing wrong?

Answer

John Humphreys - w00te picture John Humphreys - w00te · Feb 14, 2012

Are your \'s supposed to be /'s or am I just confused about your environment?

UNIX MAN page:

 #include <fcntl.h>
 #include <sys/types.h>
 #include <sys/stat.h>

 int stat(const char *restrict path, struct stat *restrict buf);

If you're on Windows (which I'm guessing you might be because of the \'s), then I can't help because I didn't even know that had stat.