In the below program write() returns -1 while writing to a file.
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main() {
int fd_r=0,fd_w=0;
int w_ret=100;
fd_r = open("reader.txt", O_RDONLY);
fd_w = open("writer.txt",O_CREAT,S_IRWXU);
char *buf = (char *)malloc(50);
while(read(fd_r,buf,30))
{
w_ret = write(fd_w,buf,30);
printf("%d", w_ret);
}
}
Questions: I am unable to debug why this is happening. Correction of code and suggestions as to how to debug such issues are highly appreciated
I don’t believe that
O_CREATis valid by itself for the flags: tryO_CREAT | O_WRONLY.One way to debug would be checking that the fd_w file descriptor is valid when you first open it.
“The parameter flags is one of O_RDONLY, O_WRONLY or O_RDWR which request opening the file read-only, write-only or read/write, respectively, bitwise-or’d with zero or more of the following…” http://www.linuxmanpages.com/man2/open.2.php