how to run and modify a cmd script or file in c -
@echo off set "yourdir=c:\users\asus\desktop" echo:list files: %%a in ("%yourdir%\*") echo %%~fa echo:list directories: /d %%a in ("%yourdir%\*") echo %%~fa echo:list directories , files in 1 command: /f "usebackq tokens=*" %%a in (`dir /b "%yourdir%\*"`) echo %yourdir%\%%~a pause
i have cmd
script , want include , run in c
script
and if possible modify (the cmd
script contains variables ).
do have solution ?
update
you can create script file on-the-fly in c program call from. note must handle characters "
, \
, %
specially when part of string literal, using \"
, \\
, %%
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 files:\n"); fprintf (fp, "for %%%%a in (\"%%%s%%\\*\") echo %%%%~fa\n", dirname); fprintf (fp, "\n"); fprintf (fp, "echo:list directories:\n"); fprintf (fp, "for /d %%%%a in (\"%%%s%%\\*\") echo %%%%~fa\n", dirname); fprintf (fp, "\n"); fprintf (fp, "echo:list directories , files in 1 command:\n"); fprintf (fp, "for /f \"usebackq tokens=*\" %%%%a in (`dir /b \"%%%s%%\\*\"`) 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); }
script file generated:
@echo off set "mydirectory=c:\users\asus\desktop" echo:list files: %%a in ("%mydirectory%\*") echo %%~fa echo:list directories: /d %%a in ("%mydirectory%\*") echo %%~fa echo:list directories , files in 1 command: /f "usebackq tokens=*" %%a in (`dir /b "%mydirectory%\*"`) echo %mydirectory%\%%~a pause
Comments
Post a Comment