gpt4 book ai didi

c - 将变量添加到文件路径

转载 作者:太空宇宙 更新时间:2023-11-04 05:55:08 25 4
gpt4 key购买 nike

我获得了用户 ID 以将其添加到文件路径中。但是我在创建文件时遇到了问题。如何将用户标识添加到文件路径?我使用了 strcpy 但这似乎不起作用。这是我的代码。

  mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
register struct passwd *pw;
register uid_t uid;
uid = geteuid ();
pw = getpwuid (uid);
char str[1000];
strcpy(str, "/home/" );
strcpy(str, pw->pw_name );
strcpy(str, "/Documents/test.txt" );
int openFile = creat(str, mode);

最佳答案

三次 strcpy() ?也许你想要:

strcpy(str, "/home/");
strcat(str, pw->pw_name);
strcat(str, "/Documents/test.txt");

?或者更好:

int ret;
ret = snprintf(str, sizeof str, "%s/%s/%s"
, "/home" , pw->pw_name, "Documents/test.txt");
if (ret >= sizeof str) {... error...}

关于c - 将变量添加到文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29357893/

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