C 将变量添加到文件路径中
我获得了将其添加到文件路径的用户id。但是我在创建文件时遇到了问题。如何将用户id添加到文件路径?我使用了strcpy,但似乎不起作用。这是我的密码C 将变量添加到文件路径中,c,file,strcpy,C,File,Strcpy,我获得了将其添加到文件路径的用户id。但是我在创建文件时遇到了问题。如何将用户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]; strcp
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);
这对于snprintf(在stdio.h中)是一个很好的用途。一行:
snprintf(str, 1000, "/home/%s/Documents/test.txt", pw->pw_name);
最好先验证pw->pw_name不是空的
多个strcpy不起作用的原因是每次调用时都会写入内存中的同一位置
我不建议您这样做,但您可以使用strcpy,只要您在每次调用后更新指针。一个例子:
char *loc = str;
strcpy(loc, "/home/" );
loc += strlen("/home/");
strcpy(loc, pw->pw_name );
loc += strlen(pw->pw_name);
strcpy(loc, "/Documents/test.txt" );
但是,如果您选择了一个小缓冲区(比所有三个字符串的字符总数加上一个以上的终止空字符数都要短),这将是一个问题—缓冲区溢出
snprintf的好处是确保您不会超过该界限:
函数snprintf()和vsnprintf()的写入长度不超过大小字节(包括终止的空字节('\0'))
这对于snprintf(在stdio.h中)是一个很好的用途。一行:
snprintf(str, 1000, "/home/%s/Documents/test.txt", pw->pw_name);
最好先验证pw->pw_name不是空的
多个strcpy不起作用的原因是每次调用时都会写入内存中的同一位置
我不建议您这样做,但您可以使用strcpy,只要您在每次调用后更新指针。一个例子:
char *loc = str;
strcpy(loc, "/home/" );
loc += strlen("/home/");
strcpy(loc, pw->pw_name );
loc += strlen(pw->pw_name);
strcpy(loc, "/Documents/test.txt" );
但是,如果您选择了一个小缓冲区(比所有三个字符串的字符总数加上一个以上的终止空字符数都要短),这将是一个问题—缓冲区溢出
snprintf的好处是确保您不会超过该界限:
函数snprintf()和vsnprintf()的写入长度不超过大小字节(包括终止的空字节('\0'))
三倍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...}
三倍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...}
三倍strcpy()???也许你想要strcpy(…);strcat(…);strcat(…)?或者更好的“
ret=snprintf(str,sizeof str,“%s/%s/%s”“/home”,pw->pw_name,“Documents/test.txt”);如果(ret>=sizeof str){…error…}
谢谢,把它作为一个答案添加到我可以把你标记为正确的strcpy()三次?也许你想要strcpy(…);strcat(…);strcat(…);strcat(…)?或者更好的“ret=snprintf(str,sizeof str),str,“%s/%s/%s”“/home”,pw->pw_name,“Documents/test.txt”);如果(ret>=sizeof str){…error…}
谢谢,请将其添加为我的答案,我可以将您标记为正确。我强烈建议使用sizeof str
而不是幻数。我强烈建议使用sizeof str
而不是幻数