How to use a terminal command's output in my program? - c

I want to parse the output of the command w for use in my program
I know i can execute w using execlp but is there a way to get the output from w into my program directly? I'm thinking i could use a pipe or something, but I don't know very much about it or how pipes work in an execlp command.
Thanks for the help

Look at popen for a simple way to do that, although it has various weaknesses (calling out to the shell, for example). libslack also has a popen replacement (the coprocess functions); it is under the GPL.

Use popen(3):
#include <stdio.h>
main()
{
char *command="w";
FILE *fpipe = (FILE*)popen(command,"r")) );
char line[256];
while ( fgets( line, sizeof(line), fpipe))
{
printf("%s", line);
}
pclose(fpipe);
}

man popen
(some other random characters to get past lame filter)

Related

get the text printed due to executing cmd command in c

I have a binary file which prints the result instead of returning the value, if I execute it using cmd I am getting printed text, I managed to execute it from C code but it seems like I can not get the text it usually prints to be stored in a variable I can use later for further decisions.
I do not have that much of experience in C and I googled a lot.
I came across the idea of using clip but my cmd is saying that clip command can not be found.
any help or ideas would be appreciated.
The correct function pair to use on POSIX systems is popen() and
pclose(). You can perhaps use Microsoft's _popen() and
_pclose() unless the warning 'This API cannot be used in applications that execute in the Windows Runtime' matters to you.
You would use it more or less like this. I've had to invent the name of the command you wish to execute since the question doesn't specify that. I chose ./example.exe as the name — and I'm assuming it needs no arguments.
char cmd[] = "./example.exe";
FILE *fp = popen(cmd, "r");
if (fp != NULL)
{
char buffer[4096];
size_t nbytes;
while ((nbytes = fread(buffer, sizeof(buffer), sizeof(char), fp)) != 0)
{
…process nbytes of data…
…it is not a null-terminated string unless you add the null byte…
}
pclose(fp);
}
else
{
…report error for failure to execute command…
}
You can use the system function from <stdlib.h> to run the command you want. To get the command's output, you modify your command like in this question to save the command's output to a file. Then you can use the file I/O functions in <stdio.h> to process the command output.
In Linux, you may do command substitution and pass its result as arguments to the program, Something like this
./your_program "$(/path/to/your/binary/file)"
Suppose your main is
int main(int argc,char* argv[]){
.
.
return 0;
}
Acess the arguments like argv[1] and so.
Here the $(command) does the substitution and it passes the printed values from the binary as arguments to the pgm. Hope this helps.
Use snprintf function. For e.g.
snprintf(cmdbuff, BUFFER_LEN, "dmidecode --type 17 | grep -i Size | grep -o '\\<[0-9]*\\>' | paste -sd+ | bc");
Here cmdbuff is character array where command will be stored , BUFFER_LEN is a size of the character array
Then use popen and fgets to get the output of command into some buffer as shown below
if((fd = popen(cmdbuff,"r")) != NULL)
{
fgets(buffer, BUFFER_LEN, fd);
sprintf(vnfc_configured_memory, "%s", buffer);
vnfc_configured_totalRAM = atof(vnfc_configured_memory);
}

C - popen not showing right output

anyone know how I can fix this?
char bash_cmd[256] = "curl";
char buffer[1000];
FILE *pipe;
int len;
pipe = popen(bash_cmd, "r");
if (NULL == pipe) {
perror("pipe");
exit(1);
}
fgets(buffer, sizeof(buffer), pipe);
printf("OUTPUT: %s", buffer);
pclose(pipe);
The above code snippit is returning the following:
OUTPUT: (�3B
instead of what it should be returning which is:
curl: try 'curl --help' or 'curl --manual' for more information
Something is wrong, I can't figure out what. When I replace "curl" with, say, "ls -la" it works fine, but for whatever reason only when I use curl, it doesn't properly save the output into buffer. What could I do to fix this?? thanks in advance
Also, replacing "curl" with the full path to curl, (/usr/bin/curl) doesn't work either. ;(
When I run your code, I find that the output is indeed approximately what you describe, but that the output you expect is also printed immediately previous. It seems highly likely, therefore, that curl is printing the usage message to its stderr rather than to its stdout, as indeed it should do.
You do not check the return value of fgets(); I suspect you would find that it is NULL, indicating that the end of the stream occurred before any data was read. In that case, I do not think fgets() modifies the provided buffer.
If you want to capture curl's stderr in addition to its stdout, then you can apply I/O redirection to the problem:
char bash_cmd[256] = "curl 2>&1";
That would not work (directly) with the execve()-family functions, but popen() runs the given command via a shell, which should handle the redirection operator just fine.
For general purposes, however, combining curl's output and error streams may not be what you want. If both real output and real diagnostics were emitted then they would be intermingled.
The output you expect from curl is going to stderr not stdout. In fact nothing is written to stdout. The output you are printing is the uninitialized contents of the buffer.
Your code should check the return value of fgets, which will be null if no characters were read (or if an error occurred).

how to read from stdout in C

I need to write a C program (myprogram) which checks output of other programs. It should basically work like this:
./otherprogram | ./myprogram
But I could not find how to read line-by-line from stdout (or the pipe), and then write all this to stdout.
One program's stdout becomes the next program's stdin. Just read from stdin and you will be fine.
The shell, when it runs myprogram, will connect everything for you.
BTW, here is the bash code responsible:
http://git.savannah.gnu.org/cgit/bash.git/tree/execute_cmd.c
Look for execute_pipeline. No, the code is not easy to follow, but it fully explains it.
Create an executable using:
#include <stdio.h>
int main()
{
char line[BUFSIZ];
while ( fgets(line, BUFSIZ, stdin) != NULL )
{
// Do something with the line of text
}
}
Then you can pipe the output of any program to it, read the contents line by line, do something with each line of text.

Help with a slight issue in reading in a text file using the '<' redirection operator in command line? C

I've searched high and low, but can not find the answer to what I would've thought to be a rather simple question. I'm rather new to C, and due to the restrictions placed on me during this project I'm having a bit of trouble figuring out how to do this.
I am trying to read in text from a text file, and store that data in an array. Simple enough. HOWEVER, I'm forced to do so by using the command line operator '<' and to redirect the stdin to the text file.
The only way I can seem to figure out how to properly open a file and perform the subsequent operations is the following:
#include <stdio.h>
FILE *fr;
main()
{
fr = fopen ("mytext.txt", "r"); /* open the file for reading */
The problem with that is that I can't seem to get the first parameter of fopen() to be the filename provided by the stdin '<'. It only works if I explicitly type a string in for the parameter. For example, if I were to run
myprog.o < mytxt.txt
how could I pass the name of the text file provided by that stdin redirection to the fopen function? Or is there a different/better way to do what I'm trying to do?
Thanks in advance.
You need to read from stdin instead of trying to open the file directly.
This is because of how redirection works - think of it a bit like this:
The file is opened (for purposes of demonstration, let's say fopen is used for this).
The existing stdin is closed. It no longer refers to a terminal or similar construct.
stdin is replaced with the open file in step 1.
Any reads from stdin now work directly from the input file.
By using input redirection you can permit your user to either redirect a file or directly type content into your program.
As for your actual problem, you might be better off passing the filename as an argument to your program. You would use argv and call your program like so:
myprog.o mytxt.txt
In this case, argv[1] will be mytxt.txt.
A C program never sees the redirection because it is handled by the shell. The C program should look at argc and read from stdin if no args are given or from the given files otherwise.
There is a standard FILE* handle declared within <stdio.h> that points to the standard input for the executing process. Such file handle is called stdin.
If all you ever want this program to do is read from standard input, then you don't need to open any files. The OS and C libraries will handle opening and closing the file for you.
So to read a file in from standard input, and write it back out, try something as simple as
#include <stdio.h>
int main( int argc, char ** argv ) {
int ch = getchar();
while ( ch != EOF ) {
putchar( ch );
ch = getchar();
}
}
As you can see, no opening or closing of files. putchar and getchar write to stdin and stdout relatively.
If you want to be more explicit, you can use the predefined file handles.
int ch = fgetc( stdin );
while ( ch != EOF ) {
fputc( ch, stdout );
ch = fgetc( stdin );
}
You should look up printf() and fprintf(), scanf() and fscanf(), and all the other wonderful stdio functions.

output redirection in Unix and C

I am trying to run a script inside my C program using system() command. Inside main(), I run the script and it returns the results. How can I put the result of the script in some string and check for conditions? I know I can do it with files but was wondering if its possible to put the result into a string.
Sample would be like:
main()
{
system("my_script_sh"); // How can I get the result of the my_script_sh
}
You can't use the system command for that. The best thing to do is use popen:
FILE *stream;
char buffer[150];
stream = popen("ls", "r");
while ( fgets(buffer, 150, stream) != NULL ){
// Copy the buffer to your output string etc.
}
pclose(stream);
Use popen() and read the stream into a char * buffer.
Well the easiest thing to do would be to take system("my_script_sh") out of your program and invoke the program from the shell with a pipe -- e.g.: my_script_sh | ./your_c_program and then your C program just reads from stdin (file descriptor 0).
If that is not possible, then have a look at man 3 popen. Basically, you use popen instead of system and it gives you a file handle that you can read from to get the output of the program.
Here are a few links that might be useful:
http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html
http://www.crasseux.com/books/ctutorial/Programming-with-pipes.html
http://www.metalshell.com/source_code/23/Popen.html
http://tldp.org/LDP/lpg/node12.html

Resources