C Programming - Stat system call - Error

stat system call geeksforgeeks
sys/stat.h in c
fstat in c
st_mtime
stat a directory
s_isdir
st_size
s_isreg

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!

Аркадий


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);
}

stat(2) - Linux manual page, STAT(2) Linux Programmer's Manual STAT(2) The stat structure All of these system calls return a stat structure, which ERRORS top C library/kernel differences Over time, increases in the size of the stat structure have  Looking for how to learn c programming? Search now! eTour.com is the newest place to search, delivering top results from across the web.


These things are a lot easier to deal with if you know the exact error. Try

printf("error = %d: %s", errno, strerror(errno));

Stat System Call Linux Tutorial – Linux Hint, To use the stat system call in C programming language, you have to include is executed successfully, 0 is returned if there are any errors, -1 will be returned. Take Advantage of the Many Sites With Information on Positions in Technology. Find c programmer


One common problem with this kind of code is using just the filename as path name. The d_name entry of dirent structure does not provide you full pathname but provides pathname relative to your directory.

To resolve this you can either

  1. construct the full path name and then pass it to stat or

  2. chdir to the directory before calling stat.

stat (system call), System Call). stat is a system call that is used to determine information about a file based on its file path. stat page. return value, Returns a negative value on failure. Running the program with the files testProgram.c. $ . With complementary support for Python and web tech. Try it free


The direct answer to the question is covered by other answers. I'm providing this as a complimentary answer. While you're debugging stat() system call, you may find the following function helpful for nicely formatting the stat buffer that's returned.

How to format, and print or log stat() system call:

static void logstat(struct stat *sp)
{
    int mode = sp->st_mode;

    if (sp->st_size > 1000000000)
        printf("  File Size:        %lluGB\n", sp->st_size / 1000000000);
    else if(sp->st_size > 1000000)
        printf("  File Size:        %lluMB\n", sp->st_size / 1000000);
    else
        printf("  File Size:        %llu bytes\n", sp->st_size);

    printf("  Number of Links:  %d\n", sp->st_nlink);
    printf("  File inode:       %d\n", sp->st_ino);
    printf("  File type:        ");
    switch (mode & S_IFMT) {
    case S_IFBLK:
        printf("BLK\n");
        break;
    case S_IFCHR:
        printf("CHR\n");
        break;
    case S_IFDIR:
        printf("DIR\n");
        break;
    case S_IFIFO:
        printf("FIFO\n");
        break;
    case S_IFLNK:
        printf("LINK\n");
        break;
    case S_IFREG:
        printf("REG\n");
        break;
    case S_IFSOCK:
        printf("SOCK\n");
        break;
    }
    printf("  File Permissions: ");
    printf( (S_ISDIR(sp->st_mode)  ? "d" : "-");
    printf( (sp->st_mode & S_IRUSR) ? "r" : "-");
    printf( (sp->st_mode & S_IWUSR) ? "w" : "-");
    printf( (sp->st_mode & S_IXUSR) ? "x" : "-");
    printf( (sp->st_mode & S_IRGRP) ? "r" : "-");
    printf( (sp->st_mode & S_IWGRP) ? "w" : "-");
    printf( (sp->st_mode & S_IXGRP) ? "x" : "-");
    printf( (sp->st_mode & S_IROTH) ? "r" : "-");
    printf( (sp->st_mode & S_IWOTH) ? "w" : "-");
    printf( (sp->st_mode & S_IXOTH) ? "x" : "-");
    printf("\n\n");
}

stat (C System Call), int stat(const char *restrict path, struct stat *restrict buf); [EIO]: An error occurred while reading from the file system. The call to the stat() function stores file information in the stat structure pointed to by statbuf. The lines that follow the stat​() call format the fields in the stat structure for presentation to the user of the program. 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 na


stat, Unix Shell Programming fstat() is identical to stat(), except that the file to be stat​-ed is specified by the file descriptor filedes. All of these system calls return a stat structure, which contains the following fields: On error, -1 is returned, and errno is set appropriately. 2000, S_IFCHR, c, 020000, character special (V7). Stat System Call: Stat system call is a system call in Linux to check the status of a file such as to check when the file was accessed. The stat() system call actually returns file attributes. The file attributes of an inode are basically returned by Stat() function. An inode contains the metadata of the file.


stat() - Unix, Linux System Call, *buf is a stat type structure defined in sys/stat.h . On success the function returns 0 and fills the buf structure with file properties. On error the  stat() is a Unix system call that returns file attributes about an inode. The semantics of stat() vary between operating systems. As an example, Unix command ls uses this system call to retrieve information on files that includes: atime: time of last access mtime: time of last modification ctime: time of last status change stat appeared in Version 1 Unix. It is among the few original Unix system calls to change, with Version 4's addition of group permissions and larger file size.


C program to find file properties using stat() function, No permissions are required on the file itself, but-in the case of stat() and lstat() - execute All of these system calls return a stat structure, which contains the following fields: On error, -1 is returned, and errno is set appropriately. The following program calls stat() and displays selected fields in the returned stat structure. fstatat() The fstatat() system call is a more general interface for accessing file information which can still provide exactly the behavior of each of stat(), lstat(), and fstat().