Beep Boop
Beep Boop

Reputation: 21

c function that changes permission of file

so im trying to make a c function which uses chmod to change permissions of a file the user should be able to enter file name aswell as permissions(777) the string would then look something like this "chmod 777 file.txt". Is there a way to do this without having to make a case for each permission?

the function RemoveChar simply removes "chmod " from the string

void changeMod(char* ptrString)
{
    RemoveChar(ptrString, 6, 0);
    char *token = strtok(ptrString, " ");
    char *file = strtok(NULL, " ");
    mode_t owner, group, others;
    for(int i = 0; i < 3; i++)
    {
        for (int permission = 0; permission < 8; permission++)
        {
            if(token[i] == ((char)permission))
            {
                if(i == 0)
                {
                    owner = (permission * 100);
                }
                else if(i == 1)
                    group = (permission * 100);
                else
                {
                    others = (permission * 100);
                }
            }       
        }
    }
    chmod(file, owner|group|others);
}

this obviously doesnt work but something like that

Upvotes: 2

Views: 323

Answers (1)

zwol
zwol

Reputation: 140549

The library function you're looking for is strtoul. Note the base argument, which can be used to direct it to parse numbers in octal.

Upvotes: 4

Related Questions