How do I generate a file with suitable permissions using sprintf() & write()?

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
void main(){ char tmp[12]={0x0}; int i=13; sprintf(tmp,"%11d", i); int fd = open("transaction.txt", O_CREAT | O_RDWR); write(fd, tmp, sizeof(tmp));
}

I'm trying to write integers to a file.
because linux does not offer itoa function, I have to try to use sprintf.
but I can't read the result file.

The file created is owned by me but has permissions ------xr-x. This means that my user can't read or write the file and my group has no access at all but strangely other users can read it.

transaction.txt properties

The file is readable if I run sudo cat transaction.txt which gives 13 as expected.

How can I generate a file with suitable permissions so that is is usable.

5

1 Answer

Add the line

int fd;

and modify the open call as follows:

fd = open("transaction.txt", O_CREAT | O_WRONLY, 00644);

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like