C 如何连接字符串

C 如何连接字符串,c,string,string-concatenation,C,String,String Concatenation,当我使用目录n时,会发生gpg错误:gpg:没有这样的目录或文件,但它有 我有: 有一个密码 int s = system("echo password | gpg -c --passphrase-fd 0 directory"); 有关信息,如果我编写而不是目录“/tmp/hello.txt”,它将正常工作 “C”的问题可能不会自动将标识符的出现替换为其值。不过,预处理器会这样做。您可以定义一个宏 #define directory "/tmp/hello.txt" 然后呢 int s =

当我使用目录n时,会发生gpg错误:gpg:没有这样的目录或文件,但它有 我有:

有一个密码

int s = system("echo password | gpg -c --passphrase-fd 0 directory");
有关信息,如果我编写而不是目录“/tmp/hello.txt”,它将正常工作

C”的问题可能不会自动将标识符的出现替换为其值。不过,预处理器会这样做。您可以定义一个宏

#define directory "/tmp/hello.txt"
然后呢

int s = system("echo password | gpg -c --passphrase-fd 0 " directory);
这将在“预处理时”(甚至在编译时之前)处理字符串。另一种方法是在运行时使用
strncat
连接两个字符串:

char str[128] = "echo password | gpg -c --passphrase-fd 0 ";
strncat(str, directory, sizeof(str) - strlen(str));
为了能够重新结束字符串,您可以存储
strlen(str)
,每次写入一个空字节,然后调用
strncat

void append(const char* app) {
    static const size_t len = strlen(str);

    str[len] = '\0';
    strncat(str, app, sizeof(str) - len);
}

这是一个重复的问题,来自:

显示如何将局部变量内容传递给系统命令

以下是建议的代码,注意:
username
password
是本地变量:

char cmdbuf[256];
snprintf(cmdbuf, sizeof(cmdbuf), 
      "net use x: \\\\server1\\shares /user:%s %s", 
      username, password);
int err = system(cmdbuf);
if (err) 
{ 
    fprintf(stderr, "failed to %s\n", cmdbuf); 
        exit(EXIT_FAILURE); 
}

谢谢,但是我的目录依赖于缓冲区,所以目录不是恒定不变的,它会改变吗有其他解决方案吗]@John你可以使用它:
int s=system(str)
where
str
指的是我答案中的字符串。@John,请阅读一些关于C的介绍性文字。这不是一个“C交互式教程”网站,有很多资源……顺便说一句,如果可能的话,使用
system()
调用外部工具是应该避免的(依赖项的可管理性有问题,shell与之分叉,等等)。在这种情况下,请看,它可能适合您的需要。此外,gpg可能不在您的路径中。不要在多用户计算机上执行此操作:在执行GnuPG时,每个人都可以读取您的密码短语!感谢之前修复的错误,但发生了另一个错误sh:2语法“|”意外建议在您的问题后添加编辑,准确显示您的modi加密代码。
char cmdbuf[256];
snprintf(cmdbuf, sizeof(cmdbuf), 
      "net use x: \\\\server1\\shares /user:%s %s", 
      username, password);
int err = system(cmdbuf);
if (err) 
{ 
    fprintf(stderr, "failed to %s\n", cmdbuf); 
        exit(EXIT_FAILURE); 
}