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);
}
}