【问题标题】:adding a variable into a file path将变量添加到文件路径中
【发布时间】:2015-03-30 23:08:17
【问题描述】:

我获得了用户 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];
  strcpy(str, "/home/" );
  strcpy(str, pw->pw_name );
  strcpy(str, "/Documents/test.txt" );
  int openFile = creat(str, mode);

【问题讨论】:

  • 三次strcpy() ???也许你想要 strcpy(...); strcat(...); strcat(...) ?甚至更好”ret = snprintf(str, sizeof str, "%s/%s/%s" "/home" , pw->pw_name, "Documents/test.txt"); if (ret >= sizeof str) {... error...}
  • 谢谢,将其添加为我将您标记为正确的答案

标签: c file strcpy


【解决方案1】:

三次 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...}

【讨论】:

    【解决方案2】:

    这是 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" );
    

    但是,如果您选择了一个小缓冲区(比所有三个字符串的字符总和短 + 一个用于终止 null 的字符数),这将是一个问题 - 缓冲区溢出。

    snprintf 的好处是确保您不会超出该界限:

    函数 snprintf() 和 vsnprintf() 写入的字节数不超过 size 字节(包括终止空字节 ('\0'))。

    【讨论】:

    • 我强烈推荐使用sizeof str 而不是幻数
    猜你喜欢
    • 2021-02-28
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    相关资源
    最近更新 更多