【发布时间】:2019-04-08 15:11:31
【问题描述】:
我有一小段 C 代码如下。我尝试使用 2 种方法运行它。
1) Clion 使用 Cygwin64 环境
2) 使用命令提示符(在这种情况下,我必须将 cygwin1.dll 移动到与可执行文件相同的文件夹中)。
我的代码需要调用 system() 函数来运行一些 cmd 命令。
如果我尝试第一种方法,则代码可以完美运行。但是,当使用第二种方法时,system() 调用似乎什么也没做。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
FILE *fp=fopen("run.bat", "w+");
fprintf(fp,"dir > result.txt\n");
fclose(fp);
printf("Before calling System\n");
system("cmd.exe /c run.bat");
if(access("result.txt",F_OK)==0){
printf("Run completed!\n");
}
printf("After calling System\n");
}
我使用 1 得到的是“运行完成!”这一行。得到printed out normally。
但是,对于 2,没有创建“result.txt”,因此“运行完成!”行never appears。
现在我需要我的可执行文件可以在 cmd 中执行才能使用。那么有人可以帮忙吗?
【问题讨论】:
-
你检查
fopen的结果了吗?system? -
有一个run.bat文件。它只是不执行,所以我很确定这是 system() 的问题。我什至尝试了像 cls 这样的基本命令,但它不起作用。
-
我猜它会尝试使用
/bin/sh运行命令,并且在从普通的 cmd 控制台窗口运行时不可用。如果您从 Cygwin bash 终端窗口运行它,它会起作用吗? -
Cygwin 终端工作正常 :D 但我需要将此可执行文件带到其他 PC(嗯,不是这段代码,而是更大的代码),而且那里没有 Cygwind 终端。
-
如果你需要在没有 Cygwin 环境的系统上运行,那么你应该仔细考虑使用 Cygwin 构建工具。 Microsoft 的 C 编译器不是我通常推荐的编译器,但我确实希望使用该编译器构建会生成一个可执行文件,其中当程序在本机 Windows 环境中运行时,
system()函数可以正常工作。
标签: c batch-file cmd clion