How to read the command line?

Asked

Viewed 194 times

6

Let’s say I want to do a routine to automate the process of compiling a program. In general (language independent), you call compiler from the command line. For example:

javac meuPrograma.class

or

gcc meuPrograma. c -o meuPrograma

In Windows, we can use system(). But how to read the command line ? In the case of a compiler, for example, how to read the possible errors returned by the compiler on the command line. Better said, how do the Ides do it ? This would be important if we wanted to integrate any program with CLI interface to our system, not just for compilers.

  • The Dev-C++ IDE is a great example of this CLI integration. It makes use of standard utilities such as the gcc, the gdb and the make.

2 answers

6

You want to get the result of system() within your program?
Usa POSIX popen() or MSDN _popen()

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

int main(void) {
    FILE *handle;
    char cmd[] = "dir";
    char line[1000];
    int n = 0;

    handle = popen(cmd, "r"); // se der erro de linker experimenta _popen
    if (!handle) {
        perror("");
        exit(EXIT_FAILURE);
    }
    while (fgets(line, sizeof line, handle)) {
        printf("%03d: %s", ++n, line); // line includes ENTER
    }
    pclose(handle); // se der erro experimenta _pclose
}

2


The best is to put the two processes (your two programs) to talk to each other. It can be in many different ways, for example: file, shared memory, messages or socket.

As you mentioned Windows console, one possible solution in this case is to redirect the console output to a file and then print it on the console.

Your system call would look more or less like this:

gcc meuPrograma.c -o meuPrograma > arquivo.txt | type arquivo.txt

Thus, your next program could read this.txt file as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.