For homework I have to read from the standard input, save it to a file and then read the file in another process. However, I’m confused as to why this code does not work:
while((n = read(0,buf,sizeof(buf))) > 0) {
int tempfile = open("testfile", O_TRUNC | O_CREAT, 0666);
write ( tempfile , buf , sizeof(buf) );
close(tempfile);
process("testfile");
}
I’m not supposed to use any stdio stuff.
When I look at the file I’ve created, it has 0 bytes and yet the buffer itself has the correct information….can someone help em see where I’ve gone wrong?
I can use process on file names and it correctly reads them.
You’ve specified
O_TRUNC | O_CREATfor the open flags, but you’ve failed to specifyO_RDWRorO_WRONLY.You also probably want to write
nbytes, notsizeof(buf), as the remainingsizeof(buf) - nbytes are uninitialized.