gpt4 book ai didi

c - 如何在 c 中运行和修改 cmd 脚本或文件

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:49 24 4
gpt4 key购买 nike

@echo off

set "yourDir=C:\Users\asus\Desktop"

echo:List only files:
for %%a in ("%yourDir%\*") do echo %%~fa

echo:List only directories:
for /d %%a in ("%yourDir%\*") do echo %%~fa

echo:List directories and files in one command:
for /f "usebackq tokens=*" %%a in (`dir /b "%yourDir%\*"`) do echo %yourDir%\%%~a

pause

我有一个 cmd 脚本,我想在 c 脚本中包含并运行它

如果可能的话修改它(cmd 脚本包含变量)。

你有解决办法吗?

最佳答案

更新

您可以在 C 程序中即时创建一个脚本文件,您将从中调用它。请注意,您必须通过使用 \" 特别处理字符 "\ 以及 % 作为字符串文字的一部分> 和 \\%% 分别。

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

void fatal(char *msg) {
printf("%s\n", msg);
exit (1);
}

void makebat(FILE *fp, char *dirname) {
fprintf (fp, "@echo off\n");
fprintf (fp, "\n");
fprintf (fp, "set \"%s=C:\\Users\\asus\\Desktop\"\n", dirname);
fprintf (fp, "\n");
fprintf (fp, "echo:List only files:\n");
fprintf (fp, "for %%%%a in (\"%%%s%%\\*\") do echo %%%%~fa\n", dirname);
fprintf (fp, "\n");
fprintf (fp, "echo:List only directories:\n");
fprintf (fp, "for /d %%%%a in (\"%%%s%%\\*\") do echo %%%%~fa\n", dirname);
fprintf (fp, "\n");
fprintf (fp, "echo:List directories and files in one command:\n");
fprintf (fp, "for /f \"usebackq tokens=*\" %%%%a in (`dir /b \"%%%s%%\\*\"`) do echo %%%s%%\\%%%%~a\n", dirname, dirname);
fprintf (fp, "\n");
fprintf (fp, "pause\n");
}

int main(int argc, char *argv[]) {
FILE *fp;
char *fname = "MyScript.bat";
if ((fp = fopen(fname, "wt")) == NULL)
fatal("Cannot open script file");

makebat(fp, "MyDirectory");

if (fclose (fp))
fatal("Cannot close script file");
//system(fname);
return(0);
}

生成的脚本文件:

@echo off

set "MyDirectory=C:\Users\asus\Desktop"

echo:List only files:
for %%a in ("%MyDirectory%\*") do echo %%~fa

echo:List only directories:
for /d %%a in ("%MyDirectory%\*") do echo %%~fa

echo:List directories and files in one command:
for /f "usebackq tokens=*" %%a in (`dir /b "%MyDirectory%\*"`) do echo %MyDirectory%\%%~a

pause

关于c - 如何在 c 中运行和修改 cmd 脚本或文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29316718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com