I'm trying to create a C code which will create a file for which I can read or write from/to. This file can already exist, or need to be created from scratch. If it already exists within the directory, I want it to created from scratch, in other words delete all the contents.
FD = open("p.txt", O_RDWR | O_CREAT | O_TRUNC);
I've tried using that for the time being. I encounter a problem though. If the file doesn't exist, it creates it and returns a positive file descriptor.
If the file however already exists, a -1 FD is returned. So I must be missing a flag?
I assumed O_TRUNC would be enough to clear the contents of a file?
FD = open("p.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
When a Unix call returns -1, check the value of the errno variable. It contains the reason for the error. Don't speculate as to what might be the problem until you've seen the error code. You can call strerror or perror to get a message describing the numerical value stored in errno.
Also, as others have noted, when you pass O_CREAT to open, you must pass a third argument which determines the file's permission if it's created. (If you don't )
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
int fd = open("p.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd == -1) {
perror("opening p.txt");
exit(1);
}
/* … */
}
Related
This question already has answers here:
Why are the file permissions changed when creating a file with the open system call on Linux?
(3 answers)
Closed 3 years ago.
I am trying to create a file which will have read, write, execute permissions for user group and others, but this is not happening.
I tried the following command
fd = open("file1",O_CREAT| O_WRONLY, 0777);
the permissions that this gives is
rwx-xr-r-x
I want
rwxrwxrwx
I tried tinkering with other modes like
fd2 = open ("file2",O_WRONLY | O_CREAT | O_TRUNC, 0644 );
and they gave the right permissions
rw-r--r--
where am I going wrong ?
My Code
#include <fcntl.h>
#include <stdio.h>
int main(void){
int fd;
fd = open("file1",O_CREAT| O_WRONLY, 0777);
int fd2;
fd2 = open ("file2",O_WRONLY | O_CREAT | O_TRUNC, 0644 );
}
Processess have an inheritable mode_t-typed property called umask which you can set with the umask call.
When you create a filesystem item with specified permissions P, the resulting permissions are P &~ the_umask.
Example:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
mode_t getumask(void)
{
mode_t m = umask(0);
umask(m);
return m;
}
int main(void){
unlink("file1");
unlink("file2");
int fd;
mode_t cur_umask = getumask();
printf("cur_umask=%#o\n", cur_umask);
mode_t given_mode=0777;
if(0>(fd = open("file1",O_CREAT| O_WRONLY, given_mode))) return perror("open"),1;
struct stat sb;
if(0>fstat(fd,&sb)) return perror("fstat"),1;
close(fd);
printf("given_mode=%#o mode=%#o expected_mode=%#o\n", given_mode, 0777&sb.st_mode, given_mode&~cur_umask);
//Without cur_umask
int r=0;
mode_t oldumask = umask(0);
given_mode=0777;
if(0>(fd = open("file2",O_CREAT| O_WRONLY, given_mode))) return perror("open"),1;
if(0>fstat(fd,&sb)) return perror("fstat"),1;
printf("given_mode=%#o mode=%#o expected_mode=%#o\n", given_mode, 0777&sb.st_mode, given_mode);
out:umask(oldumask);
return r;
}
Possible example output:
cur_umask=027
given_mode=0777 mode=0750 expected_mode=0750
given_mode=0777 mode=0777 expected_mode=0777
Usually, umask is set with the umask shell builtin in one of your loggin-session startup scripts (e.g., /etc/profile) and is then inherited to descendant processes.
If you want your C process to create filesystem items with permissions exactly as specified, you need to zero your umask before creating your items. Keep in mind that if you intend to exec after the umask change you might want to restore the old value before you exec.
I came across this piece of code and it is not supposed to work according to the author, however, it runs successfully. The author recommends the use of O_CREAT which does the same thing but guarantees atomicity. In my opinion whether two processes are running concurrently or not, the code should still work?
if((fd=open("filename.dat", O_WRONLY) < 0)){
if(errno != ENOENT){
perror("open error");
exit(1);
}
else if((fd=open("filename.dat", O_WRONLY | O_CREAT)) < 0){
perror("creation error");
exit(1);
}
}
Atomicity is provided by the operating system: either the file exists, or it doesn't, however, between the calls to e.g. access() to check for existence and open() to create the file, another process may have created the file. So atomically creating a file must be done in one call:
if ((fd=open("filename.dat", O_WRONLY | O_CREAT | O_EXCL, mode))<0) {
// file exists or other error
O_EXCL results in the call failing when the file exists.
mode is a parameter required with O_CREAT to specify the file's access/sharing permission. The flags differ between Linux and Windows.
I have opened a text file named "pranav" in O_APPEND | O_CREAT mode as shown below:
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
main()
{
//FILE Descriptor fdes
/*Open file pranav.txt in write-only mode,
O_CREAT creates file if it does not exist*/
int fdes = open("pranav.txt",O_APPEND | O_CREAT );
//Error returns -1
if(fdes!=-1)
{
//To write on file
if((write(fdes,"Pranav",6))== -1)
write(2,"File_Writing_Error",18);
//To print on screen
else
write(1,"Done",4);
}
else
{
//Print "error" on screen
write(2,"File_Opening_Error",18);
}
close(fdes);
}
In O_APPEND mode it executes the write(2,"File_Writing_Error",18); statement, thus not able to write "Pranav" on file, but this error does not occur and program successfully runs if I use O_WRONLY mode
Documentation for open says, that you must give exactly one of the flags O_RDONLY, O_WRONLY and O_RDWR and that you can use any combination of the other flags like O_APPEND and O_CREAT.
You did not provide O_WRONLY in addition to O_APPEND and O_CREAT. My guess is that O_RDONLY is 0, so when not giving one of the access flags you end up with O_RDONLY and thus cannot write to the file.
So the correct code should be:
mode_t mode = S_IRWXU | SIRWXG; // or any other mode
int fdes = open("pranav.txt", O_APPEND | O_CREAT | O_WRONLY, mode);
Please note the additional parameter mode which is required if the flags included O_CREAT or O_TMPFILE.
I have 10 processes which try open the same file more or less at the same time using open(O_CREAT) call, then delete it. Is there any robust way to find out which process actually did create the file and which did open already create file, for instance, if I want to accurately count how many times that file was opened in such scenario.
I guess I could put a global mutex on file open operation, and do a sequence of open() calls using O_CREAT and O_EXCL flags, but that doesn't fit my definition of "robust".
Use O_EXCL flag with O_CREAT. This will fail if the file exists and errno will be set to EEXIST. If it does fail
then attempt open again without O_CREAT and without O_EXCL modes.
e.g.
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);
if ((fd == -1) && (EEXIST == errno))
{
/* open the existing file with write flag */
fd = open(path, O_WRONLY);
}
Based roughly on your comments, you want something along the lines of this function:
/* return the fd or negative on error (check errno);
how is 1 if created, or 0 if opened */
int create_or_open (const char *path, int create_flags, int open_flags,
int *how) {
int fd;
create_flags |= (O_CREAT|O_EXCL);
open_flags &= ~(O_CREAT|O_EXCL);
for (;;) {
*how = 1;
fd = open(path, create_flags);
if (fd >= 0) break;
if (errno != EEXIST) break;
*how = 0;
fd = open(path, open_flags);
if (fd >= 0) break;
if (errno != ENOENT) break;
}
return fd;
}
This solution is not bullet proof. There may be cases (symbolic links maybe?) that would cause it to loop forever. Also, it may live-lock in certain concurrency scenarios. I'll leave resolving such issues as an exercise. :-)
In your edited question, you pose:
I have 10 processes which try open the same file more or less at the same time using open(O_CREAT) call, then delete it.
A hack-ish, but more bullet proof, solution would be to give each process a different user ID. Then, just use the regular open(path, O_CREAT|...) call. You can then query the file with fstat() on the file descriptor, and check the st_uid field of the stat structure. If the field equals the processes' user ID, then it was the creator. Otherwise, it was an opener. This works since each process deletes the file after opening.
I created this file
char *output = "big";
creat(output, O_RDWR);
When I'm trying to read the file
cat big
I'm getting permission denied. Whats wrong with my code? How to create a file with read and write permission mode?
with ls -l, the permission of big looked like this
----------
what does this mean?
You have misinterpeted the mode argument. From the man page:
mode specifies the permissions to use in case a new file is cre‐
ated. This argument must be supplied when O_CREAT is specified
in flags; if O_CREAT is not specified, then mode is ignored.
The effective permissions are modified by the process's umask in
the usual way: The permissions of the created file are
(mode & ~umask). Note that this mode only applies to future
accesses of the newly created file; the open() call that creates
a read-only file may well return a read/write file descriptor.
and also
creat() is equivalent to open() with flags equal to
O_CREAT|O_WRONLY|O_TRUNC.
So, a more appropriate call might look like:
int fd = creat(output, 0644); /*-rw-r--r-- */
If you want to open it O_RDWR though, then just use open():
int fd = open(output, O_CREAT|O_RDWR|O_TRUNC, 0644);
This is obviously a permission issue, start trying to see if creat doesn't returns -1, if so, print the errno value, with perror(""), so that you could resolve the problem.
Imho, i'd rather use open() to do this, because as mentionned in the creat man page,
"Note that open() can open device special files, but creat() cannot create them; ..", and
"creat() is equivalent to open() with flags equals to O_CREAT | O_WRONLY | O_TRUNC", and this doesn't talks about the permissions..
it would be the exact same result if you did this:
char* output = "big";
int fd;
fd = open(output, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
// do whaterver you want to do in your file
close(fd);
For more information, "man 2 open"