简体   繁体   中英

how to run and modify a cmd script or file in c

@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

i have a cmd script and i want to include and run it in a c script

and if possible modify it (the cmd script contains variables ).

do you have a solution ?

UPDATE

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);
}

Script file generated:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM