Copy a file using UNIX-system calls

#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>

int main( int argc,char *argv[] )
{
    char buf;
    int sourcefile,destfile,n;
    if(argc!=3)
    {
        write(STDOUT_FILENO,"prgm1 <sourcefile> <destination file>\n",50);   
        exit(1);
    }
    else
    {
         sourcefile=open(argv[1],O_RDONLY);
         if(sourcefile==-1)
         {
            perror("SOURCE FILE ERROR");
            exit(0);
         }
         else
         {
            destfile=open(argv[2],O_WRONLY | O_CREAT , 0641);
            if(destfile==-1)
            {
                perror("DESTINATION FILE ERROR");
                exit(0);
            }
            else
            {
                while((n=read(sourcefile,&buf,1)) != -1)
                {
                    write( destfile, &buf, 1 );
                }
                write(STDOUT_FILENO, "FILES COPIED\n" , 15);    
                close(sourcefile);
                close(destfile);
            }
        }
    }
    return 0;
}

the value returned by read() (n) never becomes -1 ? why?
:confused:

read returns 0 on EOF, -1 on error. EOF is not an error.

well in my textbook it says

so , should'nt it return -1 once it reaches the EOF and tries to read the next byte?

so , does it mean that even after the EOF is reached and it tries to read the next byte, it continues to "read" from the "stream"? eventhough there is nothing to read?

i guess i misunderstood this...
thanks,problem solved

ok, i have another doubt on open()
i change my c-code
from

sourcefile=open(argv[1],O_RDONLY);

to

sourcefile=open(argv[1],O_RDONLY,0664);

shouldn't open() be able to override the default permissions already set?
i tried and apparently it does not. is there any reason, besides enforcing security(that the only thing that i could think of)? and is there any way around this? (besides giving the file permissions using the system("chmod "); function?)

The third option to open() - which is shown in man pages as "..." is only used when a new file is being created. In your case you are opening an existing file as read only.

"..." is a way of saying that the number and types of the remaining arguments may vary. There may be none or there may be one or more.

That's not the preferred way to specify file modes in UNIX. By not giving it the O_CREAT file it means that the file exists and the open call will have no affect on it and instead of giving 0644 for the file mode bits use...

sourcefile=open(argv[1], O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH);

That's for creating and opening a file that does not exist because if it does then the open call fails so should check its return value.

Do not use a textbook, reference the man page for read. There are a lot of reasons for doing using the man page, you've discovered the first one.

man 2 read