Click to See Complete Forum and Search --> : system prg


bsamuels
10-09-2003, 03:55 PM
New to unix/linux I am writing a simple backup utility that will copy listed files or directories to another directory. The heart of the prg will be a routine that opens a file and copies it using the same name and permission bits to a directory specified as an argument. The permissions part I will get to later, My first pass:
void copyfile (char filename[],char destdir[])
{
int in_fd, out_fd, n_chars;
char buf[BUFFERSIZE];
char * pathname = strcat(strcat( strcat("./", destdir),"/"),filename);


/* open files */

if ( (in_fd=open(filename, O_RDONLY)) == -1 )
oops("Cannot open ", filename);

if ( (out_fd=creat( destdir, COPYMODE)) == -1 )
oops( "Cannot creat", pathname);

/* copy files */

while ( (n_chars = read(in_fd , buf, BUFFERSIZE)) > 0 )
if ( write( out_fd, buf, n_chars ) != n_chars )
oops("Write error to ", pathname);
if ( n_chars == -1 )
oops("Read error from ", filename);

/* close files */

if ( close(in_fd) == -1 || close(out_fd) == -1 )
oops("Error closing files","");
}

has the obvious problem of trying to write to a directory as a file. Once I open a file for reading, how do I write it to a directory using system calls?

bsamuels
10-09-2003, 10:31 PM
I figured this one out, using the call to chdir before the call to write.

goon12
10-10-2003, 08:50 AM
I actually have a question about using read/write instead of using something like fread, and fwrite.. What are the pros/cons to using either one?


I have a very similar program to yours, that uses fread/fwrite.


-goon12

bsamuels
10-10-2003, 09:04 AM
fread and ffwrite are Standard C braryLicalls and as a result incur some overhead as they are implemented with the very system calls that you can use directly.