How to pass a .sh file as a parameter to a code in C?

0

I need to pass as a parameter to a program in C a file with .sh extension. I already tried it and the value that is read from the file is wrong: ./program ./file.sh

How do I get past this argument? Do I need to add anything to make? Thank you

    
asked by anonymous 27.10.2015 / 12:05

2 answers

3

You can use the argc and argv[] arguments of the main function. The argc and argv parameters give the programmer access to the command line with which the program was invoked.

The% count (argument count) is an integer and has the number of arguments with which the argc function was called on the command line.

The main() (argument values) is a vector of strings. Each string of this vector is one of the command line parameters. It is to know how many elements we have in argv we have argv .

See an example of a program that takes the path of a .h file as a parameter:

#include <stdio.h>

int main(int argc, char * argv[])
{
    char *caminho_arquivo;

    if (argc == 2) /*Quantidade de parâmetros.*/
        caminho_arquivo = argv[1];

    printf("\nCaminho: %s\n\n", caminho_arquivo);

    return 0;
}

Input, the program runs with two parameters, they are, executable name and file path .h : argc

Output: ./exemplo1 /home/user\ joao/arquivo.h

If you are using linux and if the path of your .h file contains whitespace, you should format them using /home/user joao/arquivo.h for example: \ should be /home/user joao/arquivo.h .

Font .

    
27.10.2015 / 16:50
0

Although your question has gotten a bit vague (due to missing code example), here's a possible solution.

Programs in language C have as argument to their main main method the amount of arguments received and an array with these arguments.

Here is a code example where you can access arguments received from the command line:

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    printf( argv[1] );
}

Note: The zero index argument is always the name of the program itself in C.

    
27.10.2015 / 12:18