gpt4 book ai didi

C - dir 路径最后一个文件夹 - 最后是乱码

转载 作者:行者123 更新时间:2023-12-01 13:27:39 25 4
gpt4 key购买 nike

我想获取目录路径中的最后一个文件夹。

例如我有这个目录路径:

/home/workspace/projects/files/example.c

我想获取"file"

我正在使用

basename((dirname("/home/workspace/projects/files/example.c")));

我想将"file"导出到 .csv 文件,但最后出现乱码,类似于"file"

更新:我也试过这个:

  char * path = strdup(file);
basename(dirname(path));

char * 文件指向“/home/workspace/projects/files/example.c”而且它也不起作用,"file"最后仍然用垃圾写入.csv,但是当我打印 basename(dirname(file)) 来控制台时,它打印得很好"file"

最佳答案

如评论中所述,dirnamebasename 都可以修改传递给它的参数。但是,您传递的是一个字符串文字,无法修改。尝试这样做会调用 undefined behavior ,在这种特殊情况下会导致打印额外的字符。

C standard 的第 6.4.5 节关于字符串文字说明如下:

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

您需要将此字符串存储在数组或动态分配的缓冲区中。然后就可以修改了。

char path[] = "/home/workspace/projects/files/example.c";
basename((dirname(path)));

这里,path 被声明为一个数组,并且这个数组被初始化 为一个字符串文字。它本身不是字符串文字。

关于C - dir 路径最后一个文件夹 - 最后是乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47702727/

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