将字符串变量传递给包含 C 中的 system() 命令的函数

Passing string variable to function containing system() command in C

我知道关于此主题的其他帖子。但是看完之后,我的情况好像还是有问题。

目前我正在开发一个 'String to speech' 函数,使用 Vbscript 将字符串转换为语音。 (spraak.vbs) VBsript 保存在与 C 代码相同的文件夹中。

带有 1 个参数的`VBscript 文件的内容

rem String to speech  
Set spkArgs = WScript.Arguments 
arg1 = spkArgs(0)
set speech =  Wscript.CreateObject("SAPI.spvoice") 
speech.speak arg1

我使用 sprintf() 命令组合了 system() 命令的总字符串。

sprintf(command, "cmd /c spraak.vbs \"Welcome\"");
system(command);

这里使用的代码很有魅力。但是当我尝试使用一个变量作为我的参数时("Welcome")。它只说 "Empty".

char text = "\"Welcome\""
sprintf(command, "cmd /c spraak.vbs %s", text);
system(command);

可能是什么问题?

下面是完整的 C 代码:

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

int main()
{
    printf("Test\n");
    char text[] = "\"Welcome\"";
    char command[] = "";
    printf("%s\n", text);
         sprintf(command, "cmd /c spraak.vbs \"Welcome\"");
         system(command);
        sprintf(command, "cmd /c spraak.vbs %s", text);
        system(command);
    printf("Test2\n");
    return 0;
}

问题是这样的:

char command[] = "";

这将创建一个 单个字符 的数组,并且该单个字符是字符串终止符 '[=13=]'。等于

char command[1] = { '[=11=]' };

当你使用 sprintf 时,你写出边界,你将有 undefined behavior.

要解决此问题,请使用固定大小的数组,并使用 snprintf 来避免缓冲区溢出:

char command[128];
snprintf(command, sizeof command, "cmd /c spraak.vbs %s", text);

sprintf 需要一个已分配的足够大小的缓冲区来放入其结果。但是,您的 char command[] = "" 是一个长度为 1 的字符数组(只是终止空值),这太短取完整结果。

您可能想尝试使用

char command[50];

相反。请注意,在实际应用中,50 应根据要存储的数据适当确定。为此,您可以使用 snprintf 而不是 sprintf 来计算所需的缓冲区大小。