0

_execl() 返回 -1 和错误消息“没有这样的文件或目录”,即使给定的文件在那里。当我直接在命令提示符下运行 gzip 命令时,它可以工作。我无法理解我在这里缺少什么。

#include <stdio.h>
#include <process.h>
#include <errno.h>

void main(){
int ret = _execl("cmd.exe", "gzip.exe", "C:\\Users\\user_name\\work\\Db618\\test.txt");
printf("ret: %d \t strerror: %s\n", ret, strerror(errno));
}

有人可以举例说明如何使用此功能,我在寻找解决方案时发现了另外一个 API system(),但在使用之前我想知道这两者在 Windows 平台上的区别是什么?

4

1 回答 1

1

根据_execl:你的第一个参数不需要是cmd.exe,而应该是命令行的第一个命令,比如gzip.exe

您可以参考MSDN sample.

最后,你的程序只需要删除开头的“cmd.exe”,但需要注意的是最后一个参数必须是NULL表示终止。

这是代码:

#include <stdio.h>
#include <process.h>
#include <errno.h>
#include <cstring>

int main(int argc, const char* argv[])
{
    int ret = _execl("D:\\gzip-1.3.12-1-bin\\bin\\gzip.exe" ,"-f","D:\\gzip-1.3.12-1-bin\\bin\\test.txt" ,NULL);
    printf("ret: %d \t strerror: %s\n", ret, strerror(errno));
    return 0;
}

如果你想使用system,你可以将命令作为参数传递给 ,system function就像使用 CMD 一样达到同样的效果。

你可以像这样使用它:

system("gzip.exe test.txt");
于 2020-07-30T01:45:19.453 回答