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?
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?