gpt4 book ai didi

c - 打开某个目录并在c中写入

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:19:56 25 4
gpt4 key购买 nike

我试图在 c 中实现这个 linux 命令序列:cd/文件夹/文件夹;echo 1000 > 文件;

我试过这段代码,它工作正常:

int fd, len;
char buf[MAX_BUF];
fd = open("/folder/folder" "/file", O_WRONLY);
len = snprintf(buf, sizeof(buf), "%d", 1000);
write(fd, buf, len);

但我想声明:char * a = some other folder,如果我的文件夹会改变;并使用它:

open(a "/file", O_WRONLY); 

但后来我得到错误:字符串前应为 ')'

关于如何修复它或以不同方式实现的任何想法?谢谢。

最佳答案

您只能使用邻接来连接字符串文字,而不是运行时字符串。

要执行后者,只需使用您似乎已经知道的 snprintf()!

类似于:

char fn[1024];
const char *a = "/hello/filesystem";

snprintf(fn, sizeof fn, "%s/file", a);

或者,很自然地,将整个有效路径放在变量中以开头:

const char *a = "/hello/filesystem/file";

但这很明显,所以我假设您想要一个运行时解决方案。

此外,您不是在“打开某个目录”,而是在打开某个 中的文件

最后,在依赖文件描述符有效之前检查open() 是否成功。

关于c - 打开某个目录并在c中写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670151/

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