open () and read () system calls & hellip; program not executed


I'm trying to make a program that would copy 512 bytes from 1 file to another using said system calls (I could make a couple buffers, memcpy() and then fwrite() but I want to practice with Unix specific low level I/O). Here is the beginning of the code:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

int main(int argc, char **argv)
     int src, dest, bytes_read;
     char tmp_buf[512];

     if (argc < 3)
        printf("Needs 2 arguments.");

     printf("And this message I for some reason don't see.... o_O");

     if ((src = open(argv[1], O_RDWR, 0)) == -1 || (dest = open(argv[2], O_CREAT, 0)) == -1)

     while ((bytes_read = read(src, tmp_buf, 512)) != -1)
         write(dest, tmp_buf, 512);

   return 0;

I know I didn't deal with the fact that the file read from isn't going to be a multiple of 512 in size. But first I really need to figure out 2 things:

  1. Why isn't my message showing up? No segmentation fault either, so I end up having to just C-c out of the program

  2. How exactly do those low level functions work? Is there a pointer which shifts with each system call, like say if we were using FILE *file with fwrite, where our *file would automatically increment, or do we have to increment the file pointer by hand? If so, how would we access it assuming that open() and etc. never specify a file pointer, rather just the file ID?

Any help would be great. Please. Thank you!

The reason you don't see the printed message is because you don't flush the buffers. The text should show up once the program is done though (which never happens, and why this is, is explained in a comment by trojanfoe and in an answer by paxdiablo). Simply add a newline at the end of the strings to see them.

And you have a serious error in the read/write loop. If you read less than the requested 512 bytes, you will still write 512 bytes.

Also, while you do check for errors when opening, you don't know which of the open calls that failed. And you still continue the program even if you get an error.

And finally, the functions are very simple: They call a function in the kernel which handles everything for you. If you read X bytes the file pointer is moved forward X bytes after the call is done.