'How to properly use system in C

I'm trying to open Google's Chrome with C.

I'm using Cygwin bash as my terminal and have added it to my PATH - here's my code:

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    system(" C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe ");
    return 0;
}

Yesterday I had the problem of an error showing "sh: Start: Command not found" when putting "Start" in front of the google file path.

Today, after taking out the "Start" and just leaving the file path, I'm getting the errors:

sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: ` C:\Program Files (x86)\Google\Chrome\Application\chrome.exe '

I replaced the file path of google for:

system("notepad");

and it pulls up notepad no problem.

I compile using gcc then run the executable with ./a.exe

I'm completely lost - any advice?

NOTE This is the first time asking a question here, so if I missed any valuable info please let me know



Solution 1:[1]

-- system(" C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe ");
++ system("\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\""); 

Recall that spaces, by default, are delimiters and separators that divide different parts of the command line. With your original command, your command line was parsed as:

argv[0] : C:\Program
argv[1] : Files
argv[2] : (x86)\Google\Chrome\Application\chrome.exe

In otherwords, it was trying to execute program C:\Program, with arguments Files and (x86)\Google.....

By adding quotes around it, you are telling the shell (likely CMD in your case) that you are not trying to execute C:\Program with two arguments.

Instead, the quotes clarify that you want to execute
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" as one big path to executable, including the spaces and parens within the name.

Solution 2:[2]

Get rid of the backslashes and do a

system("'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'")

or a

system("'/cygdrive/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user1934428