简体   繁体   English

C++/C:将目录移动到另一个位置

[英]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.这会将名为 Source 的文件夹移动到 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.它用 g++ 编译得很好,运行时没有错误,但它根本不移动任何东西。 Any ideas on what could be wrong?关于可能出什么问题的任何想法?

Edit: This is referring to the original post, which read FILE * src = opendir( argv[1] );编辑:这是指原始帖子,其中读取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() .函数opendir()返回一个DIR * ,它与FILE *完全不同(并且不能用作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.您必须使用readdir()从该DIR *读取目录条目,这将产生一个文件名,然后使用该信息复制该文件。

Edit: This is referring to the updated post.编辑:这是指更新后的帖子。

You don't use file functions ( fopen() , getc() etc.) on directories.您不在目录上使用文件函数( fopen()getc()等)。 The way to go is opendir() followed by readdir() , then acting on the yielded filenames.要走的路是opendir()后跟readdir() ,然后对产生的文件名进行操作。

I don't really know why fopen() on a directory actually returns a non-null pointer.我真的不知道为什么目录上的fopen()实际上返回一个非空指针。 Personally, I consider this a design flaw, as the operations possible on FILE * are not defined for directories.就个人而言,我认为这是一个设计缺陷,因为FILE *上可能的操作不是为目录定义的。 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.当你在做的时候,也检查返回值 - 他们可能会告诉你为什么事情没有按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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