-1

So, I'm trying to make a sort of ls function. Here's my code to the description of each file

struct stat fileStat;
struct dirent **files;

num_entries = scandir(filename, &files, file_select, alphasort);
stat(files[i-1]->d_name,fileStat);

for some reasons once it gets to stat it returns a -1. I was thinking it was because fileStat is not big enough to store the values, but I'm not sure how to solve that. Thanks for the help in advance!

Jose A
  • 31
  • 6

1 Answers1

0

Consider yourself to look at man pages. In short stat() returns:

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

And the errno's list is:

  • EACCES
  • EBADF
  • EFAULT
  • ELOOP
  • ENAMETOOLONG
  • ENOENT
  • ENOMEM
  • ENOTDIR
  • EOVERFLOW

After calling stat, check it's return value with and if it equals -1, check errno (with switch).

Example:

if(stat(files[i-1]->d_name,fileStat)) {
   switch(errno) {
   case EACCES:
       // Add code or at least 
       perror("STAT ERROR:");
       break;

   case EBADF:
       // ...
       break;

   case EFAULT:
       // ...
       break;

       // ...
       // Do this to all possible errno's for the stat
       // ...
   case EOVERFLOW:
       // ...
       break;
   }
}

If you have troubles with storing path, try to declare array as this (if you using linux):

#include <linux/limits.h>
//...
char current_path[PATH_MAX];

If you using Windows:

#include <windows.h>
//...
char current_path[MAX_PATH];

P.S. Thanks for Jonathan Leffler for pointing out my switch typo :)

Community
  • 1
  • 1
Mikhail Romanko
  • 396
  • 1
  • 9