Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming - Stat system call - Error

I'm new to C but trying some system calls.

I'm writing program that iterates through all files in a directory and prints the current file name and size. I can get the program to print the file name but it errors when I preform the stat system call.

Here is some of the code:

while (dptr = readdir(dirp)) { 
            if (stat(dptr->d_name, &buf) != 0) {
                //Always does this and it does print the file name
                printf("Error on when getting size of %s \n", dptr->d_name);
            } else {
                //Never gets here
                printf("%u", buf.st_size);
              }         
}

I have the structs described like this:

struct stat buf;
struct dirent *dptr;
DIR *dirp;

If I change:

if (stat(dptr->d_name, &buf) != 0)

to

if (stat(dptr->d_name, &buf) != [EACCES])

It still goes into the loop which makes me think it can't read the file name but it's printing it in the error statement without a problem.

Can someone point me in the right direction? Thanks!

Аркадий

like image 847
user795954 Avatar asked Dec 22 '22 04:12

user795954


1 Answers

First, stat() returns -1 if an error is encountered, not the actual error code. The error code will be set in errno. An easy way to print the error is to use perror().

Second, dptr->d_name only provides a relative filename of the file and not the full filename. To obtain the full filename, you must generate it from the relative filename and the directory name.

Here is an example:

int cwdloop(void)
{
   DIR           * dirp;
   struct stat     buff;
   struct dirent * dptr;
   char            filename[1024];
   char            dirname[1024];

   if (!(getcwd(dirname, 1024)))
   {
       perror("getcwd");
       return(1);
   };

   dirp = opendir(dirname);
   if (!(dirp))
   {
      perror("opendir()");
      return(1);
   };

   while ((dptr = readdir(dirp)))
   {
      snprintf(filename, 1024, "%s/%s", dirname, dptr->d_name);
      if (stat(filename, &buff) != 0)
      {
         perror("stat()");
         return(1);
      } else {
         printf("size: %u\n", (unsigned)buff.st_size);
      };
   };

   closedir(dirp);

   return(0);
}
like image 69
David M. Syzdek Avatar answered Dec 24 '22 01:12

David M. Syzdek