-1

For example i have a file test1.txt that has inside "this is a test file". and i have a directory /testDir. If i run this as ./cp2 test1.txt /testDir The program will run but test1.txt will become empty, as well as /testDir/test1.text will become empty. Can anyone identify where in my code im overwriting the contents of both text files?

Thankyou in advance.

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>  // for strtol
#include <string.h>

#define COPYMODE 0644 
#define BUFFERSIZE 1024
void errExit(char*, char*);
void copyFile(char *src, char* dest) {

int srcFd;
int dstFd;
int charCnt;
    char buf[BUFFERSIZE];

/*Check args*/

/*Open the files*/
if( (srcFd=open(src, O_RDONLY)) == -1){
    errExit("Cannot open ", src);
}
if( (dstFd=creat(dest, COPYMODE)) ==-1) {
errExit("Cannot create ", dest);
}
/*Copy the data*/
while( (charCnt= read(srcFd, buf, BUFFERSIZE)) > 0 ){
    if( write(dstFd,buf,charCnt ) != charCnt ){
    errExit("Write error to ", dest);
}
}
if( charCnt==-1 ){
    errExit("Read error from ", src);
}

/*Close files*/
if ( close(srcFd) == -1 || close(dstFd) == -1 ){
    errExit("Error closing files","");
 }

}

main(int argC, char* argV[]) {

char* src = argV[1];
char* dest = argV[2];

if(src[0] != '/' && dest[0] != '/' ) {
copyFile(src, dest);
} else if(src[0] !='/' && dest[0] == '/') { //going to change this to check if its a dir or file.
int i;
for(i=1; i<=strlen(dest); i++) {
    dest[(i-1)] = dest[i];
        }

    strcat(dest, "/");
    strcat(dest, src);
    copyFile(dest, src);
  }
 }
Yonnis
  • 3
  • 4

1 Answers1

0

There are several issues:


Your definition of COPYMODE is wrong, you need this:

#define COPYMODE S_IRWXU|S_IWUSR|S_IRGRP|S_IROTH

read the documentation of creat


This is probably not a good idea:

strcat(dest, "/");
strcat(dest, src);

here you modify the string pointed by dest. This is OK but only if the new string is not longer than the one pointed by dest, more details here.

You need another buffer for the string you construct:

char destfilename[300];
strcpy(destfilename, dest);
strcat(destfilename, "/");
strcat(destfilename, src);
copyFile(destfilename, src);
Community
  • 1
  • 1
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115