【问题标题】:How can I include a variable in remove() function? I'm trying to include an environment variable in the function如何在 remove() 函数中包含变量?我正在尝试在函数中包含一个环境变量
【发布时间】:2023-04-03 19:05:01
【问题描述】:

我正在尝试学习 C 中的 remove() 函数,我想制作一个程序,首先使用 getenv() 函数获取环境变量,然后在代码中使用它。

但是,我得到了错误

“函数 remove() 的参数太多”。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* a = getenv("USERPROFILE");
    remove("%s/Desktop/remove.txt", a);
    return 0;
}

【问题讨论】:

  • 任何像样的教科书、教程或课程都应该提到sprintf
  • %s 仅对 printf 系列函数有意义
  • 我发现 %s 不能用来做那个,但是我对如何做没有什么不同的想法,所以我决定在这里问。我是C初学者(我的经验不超过3天),我现在只知道基础。
  • 正如 Someprogrammerdude 评论的那样,使用sprintf() 创建路径名参数以传递给remove()。但请注意不要信任包括环境变量在内的用户输入,例如,如果 USERPROFILE 设置为空字符串,或者设置为另一个用户的主目录,或者根本没有设置,该怎么办?
  • 我会看看我能做什么。谢谢!

标签: c variables


【解决方案1】:

如果您只是想将它们结合起来,这应该可行。 我注释掉了一些行并放了一个 printf 以便您可以运行它来查看结果。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXPATH 256

int main()
{
    //char* a = getenv("USERPROFILE");

    char* a = "userprofile";
    char path[MAXPATH];
    strcpy(path,a);
    strcat(path,"/Desktop/remove.txt");

    //remove(path);
    printf("PATH: %s",path);
    return 0;
}

【讨论】:

  • 我在 10 分钟前设法找到了相同的方法,我意识到我可以使用 strcat。无论如何,谢谢你,祝你有美好的一天!
  • 很高兴你把它整理出来,也有美好的一天。
猜你喜欢
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 2022-10-03
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 2013-05-17
  • 2019-05-15
相关资源
最近更新 更多