使用第二个参数作为目录复制文件

标签 c malloc memcpy

我正在查看c中的复制程序,我试图理解下面的代码是如何工作的。我对这些功能进行了研究,但由于某种原因无法理解它。例如“./main a temp/” 该命令将 a 复制到文件夹 temp 中,如果第二个参数以“/”(即 temp/)结尾,则下面的代码将其指定为目录。如果用户输入“./main a b ”,则程序会复制 a 并创建与 b 具有相同文件权限的 b。我知道其他一切。除了下面的代码。有人可以解释一下下面的代码及其工作原理吗? 谢谢

if(S_ISDIR(ost.st_mode)){       //if output filename is a directory

    //concatenate directory name and input name
    int ilen = strlen(iname);
    int olen = strlen(oname);

    int len = ilen + olen + 2;
    char *copy_name = (char*) malloc(len);  //dynamically allocate a memory buffer
    if(copy_name == NULL)
        oops("Cannot malloc memory", ":");

    memcpy(copy_name, oname, olen);         //copy directory name
    copy_name[olen] = '/';                  //separate directory and file name with a slash
    memcpy(&copy_name[olen+1], iname, ilen);    //copy output file name
    return copy_name;
}else{
    return strdup(oname);   //if output filename is not a directory, just copy it
}

最佳答案

该函数的目的是返回文件路径。目标文件路径。

您已经确定该程序有两种模式。 1) 其中两个参数都是文件名,2) 其中第二个参数是文件夹。

模式1)两个参数都是文件名。

./main 旧.txt 新.txt

destinationFilePath = thisFunc("old.txt", "new.txt");
//new.txt

方式2)第二个参数是文件夹。

./main old.txt my_archive/

destinationFilePath = thisFunc("old.txt", "my_archive/");
//my_archive/old.txt

附注在这两种模式下,此代码都会返回新内存中的文件名,该内存应该被管理;它不依赖于任一参数分配的内存。

P.P.S 就像 @Jonathan 指出的那样,内存和 null 终止周围的代码质量并不好。

关于使用第二个参数作为目录复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43861295/

相关文章:

在 Windows 上使用 MinGW 编译 Openssl - fatal error : openssl/md4. h:没有这样的文件或目录

C - 在数组中使用 malloc() 存储指针,之后不能释放它们

c - 动态分配的 C 字符串存储超过指定的容量

c++ - 给定结构的双指针,使用 memcpy 将数据复制到结构成员

c++ - 复制到 vector<unsigned char> 中的无类型对象的内容

C++ memcpy 从 c_str 到 char*

c - 如何使用 "."、 "?"、 "!"计算 C 中的句子数?

c - 从C中的char数组中减去一条信息

c - 在C中的双向链表中插入

c - 如何增加函数参数指向的 block 的大小?