Click to See Complete Forum and Search --> : trying to write backup()


bsamuels
10-12-2003, 08:38 PM
I have a project to write a program to do a simple backup
of a list of files and or directories to a specified directory path. I wrote a simple copy function that takes the file path and opens the file for reading than creat's a file for writing. Of course I want the written file to have the same name as the original, but this seems tricky, How do I extract the file name from the path. here the code:

void copyfile (char filename[],char destdir[])
{
int in_fd, out_fd, n_chars;
char buf[BUFFERSIZE];
struct stat info;
struct utimbuf times; /*store files mod and access times*/
char pathbuf[PATHBUFFERSIZE];
char *currentfile;
ino_t cur;

/* open files */

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

if (stat(filename, &info) == -1) /*collect file stats*/
perror(filename);

/*collect original times into utimbuf struct*/
times.actime = info.st_atime;
times.modtime = info.st_mtime;

/*change wd */
if(chdir(destdir) == -1)
{
perror("Cannot find directory ");
return;
}


if ((out_fd=creat("newfile", info.st_mode)) == -1 ) /*use orig file permissions*/
oops( "Cannot create", filename);

/*change backup to orig times*/

if(utime("newfile",&times)== -1)
perror("Error copying mod and access time ");


rename ("newfile",filename);


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



if (chdir(pathbuf)== -1) /*reset the path to source*/
perror("Error in resetting path");

/* close files */

if ( close(in_fd) == -1 || close(out_fd) == -1 )

oops("Error closing files","");
}

Where I try to rename the file, I of course get an error, because the string is a path and not just the name.

Any help would be appreciated.

tecknophreak
10-13-2003, 08:25 AM
So you've got /usr/include/stdlib.h and you only want stdlib.h?


int pos;
char path[] = "/usr/include/stdlib.h";
for (pos = strlen(path); pos > -1 && path[pos] != '/'; --path);
++pos;
printf("%s\n", &path[pos]);


That will print stdlib.h from /usr/include/stdlib.h, it will also print stdlib.h from stdlib.h.

infidel
10-13-2003, 10:34 AM
Greetings,

Here's another way, using pointer arithmetic:

#include <stdio.h>

const char* get_filename(const char* fullpath)
{
const char* name = fullpath+strlen(fullpath)-1;
for (; *name != '/' && name >= fullpath; --name);
++name;
return name;
}

int main(int argc, char** argv)
{
printf("Full path = %s\n", argv[0]);
printf("Filename = %s\n", get_filename(argv[0]));
return 0;
}