John
John

Reputation: 25

create file and assign permissions

It seems as though whatever I put as PERMS the file created has the same permissions - rwx r-x r-x

I tried 755 and 777 and the permissions just stay the same.

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#define PERMS 0777

int main(int argc, char *argv[])
{
    int createDescriptor;
    char fileName[15]="Filename.txt";

    if ((createDescriptor = creat(fileName, PERMS )) == -1)
    {
        printf("Error creating %s", fileName);
        exit(EXIT_FAILURE);
    }

    if((close(createDescriptor))==-1)
    {
        write(2, "Error closing file.\n", 19);
    }

    return 0;
}

Upvotes: 1

Views: 826

Answers (2)

Bhushan Firake
Bhushan Firake

Reputation: 9448

Try chmod function. For more detais just right click in the IDE and type chmod.

NAME:

chmod - change mode of a file

SYNOPSIS:

 #include <sys/stat.h>
 int chmod(const char *path, mode_t mode);

DESCRIPTION:

The chmod() function shall change S_ISUID, S_ISGID, [XSI] S_ISVTX, and the file permission bits of the file named by the pathname pointed to by the path argument to the corresponding bits in the mode argument. The application shall ensure that the effective user ID of the process matches the owner of the file or the process has appropriate privileges in order to do this.

S_ISUID, S_ISGID, [XSI] S_ISVTX, and the file permission bits are described in <sys/stat.h>.

If the calling process does not have appropriate privileges, and if the group ID of the file does not match the effective group ID or one of the supplementary group IDs and if the file is a regular file, bit S_ISGID (set-group-ID on execution) in the file's mode shall be cleared upon successful return from chmod().

Additional implementation-defined restrictions may cause the S_ISUID and S_ISGID bits in mode to be ignored.

The effect on file descriptors for files open at the time of a call to chmod() is implementation-defined.

Upon successful completion, chmod() shall mark for update the st_ctime field of the file.

RETURN VALUE:

Upon successful completion, 0 shall be returned; otherwise, -1 shall be returned and errno set to indicate the error. If -1 is returned, no change to the file mode occurs. More information can be found at this link.

Upvotes: 0

Thomas
Thomas

Reputation: 181745

I think you might need to change the umask before calling creat:

umask(0000);

See man 2 umask. The default umask is often 0022 which would exactly make the difference between 0777 and 0755 vanish.

Upvotes: 5

Related Questions