Hi I’m on Linux WSL Debian and I’ve the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
int fd = open("file.dat", O_RDONLY | O_WRONLY);
write(fd, "ciao", strlen("ciao"));
close(fd);
}
Why don’t works?
2
Answers
You need the header
<unistd.h>
to get the declarations ofwrite()
andclose()
. The only other header you need is<fcntl.h>
foropen()
.I’ve also kept
<stdio.h>
so I can useperror()
ifopen()
fails.Since you’re only writing to the file, you don’t need
O_RDONLY
in the open modes. If you want to read and write, you should useO_RDWR
instead. These three flags are mutually exclusive.Note that this will not create the file if it doesn’t already exist. If you want that, you need to add the
O_CREAT
flag and another argument with the permissions that should be given to the file if it’s created.Many bugs:
unistd.h
for the declaration ofwrite
.O_RDONLY
andO_WRONLY
(andO_RDWR
) are mutually exclusive. If you want to open a file for read and write you have to useO_RDWR
. Since you are not actually reading from the file, you should useO_WRONLY
alone.O_WRONLY
withoutO_CREAT
and one (exactly one; these three are also mutually exclusive) ofO_APPEND
,O_EXCL
, andO_TRUNC
. Assuming that you do wantO_CREAT
, you must also supply a third argument, which should be the octal constant 0666 unless you have a specific reason to use some other value.write(fd, "ciao", strlen("ciao"))
should bewrite(fd, "ciaon", strlen("ciaon"))
unless you have a specific reason to be creating a text file with an incomplete last line.open
,write
, andclose
calls. (The fact thatclose
can fail is a bug in its specification, but one that we are permanently stuck with. It’s safe to ignore errors inclose
for files that were opened for reading, but not writing.)Also some style corrections:
unistd.h
,fcntl.h
, andstring.h
; it should also be includingstdio.h
, because it should also be making calls toperror
. None of the other headers should be included (unless this is cut down from a much larger program).main
asint main(void)
unless you are actually going to useargc
andargv
.main
; the last line ofmain
should bereturn 0;
.