UNIX & GNU/Linux - System calls - Using stat()

The system call stat function is designed to retrieve statistics of a file or a directory.

Simply add the path of your file or directory in the first parameter, then the variable of type struct stat in the second parameter.

The function stat returns 0 on success and -1 on error.

Let's try an example of the system call stat function:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int     main(int c, char *v[])
{
  struct stat *buf;

  buf =    malloc(sizeof(*buf));

  if (stat(v[1], buf) == 0)
    {
      printf("buf->st_dev = %d\n", buf->st_dev);
      printf("buf->st_ino = %d\n", buf->st_ino);
      printf("buf->st_mode = %d\n", buf->st_mode);
      printf("buf->st_nlink = %d\n", buf->st_nlink);
      printf("buf->st_uid = %d\n", buf->st_uid);
      printf("buf->st_gid = %d\n", buf->st_gid);
      printf("buf->st_rdev = %d\n", buf->st_rdev);
      printf("buf->st_size = %d\n", buf->st_size);
      printf("buf->st_blksize = %d\n", buf->st_blksize);
      printf("buf->st_blocks = %d\n", buf->st_blocks);
      printf("buf->st_atime = %d\n", buf->st_atime);
      printf("buf->st_mtime = %d\n", buf->st_mtime);
      printf("buf->st_ctime = %d\n", buf->st_ctime);
    }
  return (0);
}

You are now ready to create a file, named hello.bp (the extension is free of course).

Open it and write helloWorld inside.

Close it then compile and execute it:

$ gcc main.c && ./a.out hello.bp

Result will be something like that:

buf->st_dev = 64769
buf->st_ino = 6513
buf->st_mode = 33188
buf->st_nlink = 1
buf->st_uid = 75327
buf->st_gid = 32015
buf->st_rdev = 0
buf->st_size = 10
buf->st_blksize = 4096
buf->st_blocks = 8
buf->st_atime = 1302165784
buf->st_mtime = 1302165745
buf->st_ctime = 1302165745

For example, the st_size is the size in octet of the file itself. In this case: 10 (we have 10 letters of 1 octet each).
The st_atime is the moment of the last access of the file in the time format (seconds left since 1970).

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.