gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:46:10 25 4
gpt4 key购买 nike

我正在查看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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com