Embarrassingly simple question, but I can't seem to open a new file for writing using a file descriptor. Every variation I've tried returns -1
. What am I missing? This is how you initialize a file using file descriptors, correct? I can't find documentation that states otherwise.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
fd = open ("/home/CSTCIS/sample.dat", O_WRONLY, mode);
printf("%d\n", fd);
}
perror() prints open: No such file or directory
.
Quoting pubs.opengroup.org ,
Upon successful completion, the [
open
] function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1 .
To check what the problem is with the open()
statement, just write:
perror("open");
before the printf()
statement.
OP has found a solution:
The
open()
command works ifO_CREAT
flag is included.fd = open ("/home/CSTCIS/sample.dat", O_WRONLY | O_CREAT, mode);
When we are using the open() function
, we can open the file which is already present in our file structure.
If we want to create a new file, then we can use the O_CREAT
flag in open() function or we can use the creat()
function like this.
mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
fd = open ("/home/CSTCIS/sample.dat", O_WRONLY|O_CREAT, mode);
(or)
fd=creat("/home/CSTCIS/sample.dat",mode);
When we are using the creat()
function, it will open the file in read only mode.
发现问题 - 这需要包含在标志中: O_CREAT
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.