简体   繁体   中英

C++ / C: Move Directory to Another Location

I want to move the contents of one directory to another. I specify the source and destination directories via command line arguments. Here's the code:

#include <stdlib.h>
#include <stdio.h>

void move_dir(FILE *src, FILE *dest) {
    int c = getc(src);
    while(getc(src)!=EOF) {
        putc(c,dest);
    }
}

int main(int argc, char* argv[])
{
    FILE *src=fopen(argv[1]);
    FILE *dest=fopen(argv[2]);
    while(--argc>0) {
        if(src!=NULL && dest!=NULL) {
            move_dir(src,dest);
        }
    }
    fclose(src);
    fclose(dest);
    return 0;
}

For example:

./a.out /Folder1/Folder2/Source /Folder1

This will move the folder called Source inside of Folder1. However when I execute this code it doesn't work. It compiles just fine with g++ and no errors when running but it just doesn't move anything at all. Any ideas on what could be wrong?

Edit: This is referring to the original post, which read FILE * src = opendir( argv[1] ); .

The function opendir() returns a DIR * , which is quite different from a FILE * (and cannot be used as a parameter to getc() / putc() .

You have to read directory entries from that DIR * using readdir() , which will yield a filename, then copying that file using that information.

Edit: This is referring to the updated post.

You don't use file functions ( fopen() , getc() etc.) on directories. The way to go is opendir() followed by readdir() , then acting on the yielded filenames.

I don't really know why fopen() on a directory actually returns a non-null pointer. Personally, I consider this a design flaw, as the operations possible on FILE * are not defined for directories. I would stay well clear of this construct.


Generally speaking, you should read the documentation (man page) of the functions you are using, not (wrongly) assuming things about them. And while you are at it, check return values, too - they might tell you why things don't work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM