Running command line from C

I am running Windows 8 and I am using cygwin to compile my code. I am trying to execute command line commands using the system () command. It seems like it should be simple, but surprisingly I couldn't change anything. Below is my code:

#include <stdio.h>
#include <string.h>

int main ()
{
    char command[50];
    int error = 0;

    strcpy( command, "cd c:/");
    error = system(command);
    printf("%s\n", command);
    printf("%d\n", error);
    while(1)
    {
        ;
    }

    return(0);
} 

      

However, the above program simply returns the variable error as "127" and the variable as "cd c: /". Several searches in exit codes have shown that this means "127" means the command was not found. I am completely lost. I've searched for a while, but I can only find C # related questions on this issue. How do I execute command line commands from program c?

EDIT: I tried to run the program from the cygwin command line and it works fine. It just starts up incorrectly from normal cmd.exe and when I double click on the .exe file.

+3


source to share


1 answer


On Windows, 'cd' is a shell builtin command. To execute it you need to start the shell. Please check this answer .

EDIT: You can use a system command to start the shell like this:

system("<fullpath to cmd.exe>\\cmd.exe /c \"your command here\"");

      

This can get pretty tricky with escaped quotes if you haven't run a single executable after / c. If the executable or internal shell command requires parameters, you may need to double and triple the quotes. For some special characters such as | && (pipe)> (redirection) you will need to use the Windows special escape character ^ that Microsoft added for this purpose.

Here is an example of such a command. This Windows restart after a short delay:



system("cmd.exe /c \"start /b shutdown -t 1 -r\"");

      

Here's a more complex one with special screens:

system("cmd.exe /c \"ipconfig ^| find \"IPv4\" ^> C:\Users\someUser\a.txt ^&^& for /f \"tokens=13 delims=: \" %%i in (C:\Users\someUser\a.txt) do echo %%i ^> C:\Users\someUser\ip.txt ^&^& del C:\Users\someUser\a.txt\"");

      

This latter gets the ip of the machine using only simple commands and stores ip.txt in a roundabout path under the user's home directory called "someUser". Pay attention to the screens ^.

+2


source







All Articles