I'm trying to move a directory with all its contents inside another directory, and I'm stuck. I'm trying to copy every single file from the source directory to the destination one and then delete it. I'm stuck at this too. But can I do somehow with the rename()
function. If yes, how?
CODE UPDATE
void move_file(const char *name, const char *new_name) {
size_t len = 0;
char *buffer;
long lSize;
FILE *source = fopen(name, "r");
FILE *target = fopen(new_name, "w");
if (source == NULL || target == NULL) {
fprintf(stderr, "Error occurred when opening files\n");
exit(1);
}
fseek(source, 0, SEEK_END);
lSize = ftell(source);
rewind(source);
buffer = (char*)malloc(sizeof(char) * lSize);
result = fread(buffer, 1, lSize, source);
if (result != lSize) {
fprintf(stderr, "Reading error\n");
exit(2);
}
fwrite(buffer, 1, sizeof(buffer), target);
fclose(source);
fclose(target);
if (!remove(source)) {
fprintf(stderr, "Error deleting file\n");
}
}
And my second function.
void move_directory(const char *target, const char *destination) {
DIR *dir = opendir(target);
if (dir) {
char Path[256];
char *EndPtr = Path;
struct dirent *e;
strcpy(Path, target);
EndPtr += strlen(target);
while ((e = readdir(dir)) != NULL) {
struct stat info;
strcpy(EndPtr, e->d_name);
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) {
continue;
}
if (!stat(Path, &info)) {
if (S_ISDIR(info.st_mode)) {
move_directory(Path);
} else
if (S_ISREG(info.st_mode)) {
move_file(e->d_name, e->d_name);
}
}
}
}
}
I'm stuck, I don't have any ideas how I should proceed. That is what I have so far.
UPDATE: How can I now focus on my destination folder and create a folder exactly like the one I'm currently in, where my copied files should be moved into?