如何在c中运行和修改cmd脚本或文件 [英] how to run and modify a cmd script or file in c
本文介绍了如何在c中运行和修改cmd脚本或文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@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
脚本
i have a cmd
script and i want to include and run it in a c
script
如果可能,修改它( cmd
)。
and if possible modify it (the cmd
script contains variables ).
您有解决方案吗?
推荐答案
UPDATE
您可以在C程序中即时创建一个脚本文件,您将从中调用它。请注意,您必须处理字符和
\
和%
\
和 \\
和<$ c $> c> %% 。
You can create a script file on-the-fly in the C program that you will call it from. Note you must handle the characters "
and \
and %
specially when part of a string literal, by using \"
and \\
and %%
respectively.
#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中运行和修改cmd脚本或文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文