output redirection in Unix and C - 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

Related

I cannot read my .txt file in c. I am using codeblocks. I first created an array for the lines before using fgets and trying to print out the lines

I am new to C and i am trying to read a .txt file. I am using a windows 10 machine. I have created the file and i am trying to read it. I will share all my code below.
int main()
{
char firstline[255];
FILE * fpointer = fopen("klinks.txt", "r");
fgets(firstline, 255, fpointer);
printf("%s", firstline);
fclose(fpointer);
return 0;
}
Below is the message showing on the console terminal. I have no idea why.
h┐
Process returned 0 (0x0) execution time : 0.026 s
Press any key to continue.
It doesn't find the file, and the fgets call doesn't do anything, and the output is just the default garbage in firstline string.
When you create the file the program works.
Also add a check for null after the fopen call.
You need to check the value of file descriptor which is getting returned by fOpen() function just to make sure system call has not failed.
try using fread : fread reads raw data -- it will stop after a specified (or default) number of bytes, independently of any newline that might or might not be present.
You might want to check this : fgets() and fread() - What is the difference?

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);
}

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.

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

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)

Resources