简体   繁体   中英

How to read a file permission and store it in a variable in C

In Linux platform(Ubuntu system). As describe in title. I try to get a number like '0644' and store it in a variable for later use.

the stat, fstat, lstat system calls can be used to retrieve the permission of a file.
The field st_mode of the stat structure contains the permission of the file specified as argument of the system call. Then a variable of type mode_t can be used as local storage in your application.

This is an example :

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


#define FILE_NAME "test.c"

int main(int argc, char *argv[])
{
   struct stat sb;
   mode_t file_permision; 

   if (stat(FILE_NAME, &sb) == -1) {
        perror("stat");
        exit(EXIT_FAILURE);
    }

   file_permision = sb.st_mode; 
   printf(" File permission : %o (octal)\n",
            (unsigned int) file_permision); 
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM