@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
脚本包含变量)。
答案 0 :(得分:2)
<强>更新强>
您可以在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