Alejandro Sazo
Alejandro Sazo

Reputation: 795

Get basic file permissions to compare with input in C

I need to compare a basic file permission from a file with a file permission from input. The input should be saved in argv[1], and the permission information from file is stored in the classical struct stat stat_buf, specifically in the stat_buf.st_mode field.

An example of execution would be ./program 775. Then the program must say that is the same permission of some file's stat_buf.st_mode inside the code. But what I know is that the format of st_mode is tricky because it has to be read as octal, convert it to int, and so on. How to compare without problem?

Upvotes: 0

Views: 1064

Answers (2)

user529758
user529758

Reputation:

the format of st_mode is tricky because it has to be read as octal [...]

Not particularly. Just use strtoul() with an appropriate base (8):

unsigned long mode = strtoul(argv[1], NULL, 8);
if (statbuf.st_mode == mode) {
    // permissions match
}

Upvotes: 1

Alejandro Sazo
Alejandro Sazo

Reputation: 795

My approach was to build a function called oct which takes the stat_buf.st_mode, copies it to a buffer in octal mode, and again copies it to other buffer to eliminate the info I don't want (the first 3 numbers) and finally use the strtol function to get the number in decimal, to compare it with the input.

int oct(mode_t num) {
    int i;
    char buffer[7], buffer2[4];
    snprintf(buffer, 8, "%o", num);
    for(i = 0; i < strlen(buffer2); i++)
        buffer2[i] = buffer[i + 2];
    return strtol(buffer2, NULL, 10);
}

And how to test this:

int main() {
    int mode1, mode2;
    struct stat stat_buf;
    stat("/home/user/myfile", &stat_buf);
    mode1 = atoi(argv[1]);
    mode2 = oct(stat_buf.st_mode);
    printf("%d %d\n", mode1, mode2);
    return 0;
}

Example: executing ./program 775 gives as output 775 775

Upvotes: 1

Related Questions