Piping Exec/System output to a char* in C - c

Is there any way for me to run a system command such as date through my C program and pipe the output to a char *date so I can use it later? I've been trying to use the "system" command but doing system("date"); immediately prints out the date output to stdout. I want to grab this data using system or exec within my program. Any suggestions would be appreciated...
Thanks!

Take a look at popen(). You open a FILE pointer with it, like so:
#include <stdio.h>
FILE *f = popen("date", "r");
And then you can use fread() or fscanf() to read from f into your buffer of choice.

You need the function popen declared in stdio.h. Then you can read the command's output like a file.

You probably want popen()
It sets everything up for you and does what you want

You may use the following code snippet as a reference.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char *command="date";
char line[256];
if ((fp = popen(command, "r")) == NULL) {
perror("popen failed");
return -1;
}
while (fgets(line, sizeof(line), fp))
printf("%s", line);
pclose(fp);
return 0;
}

Related

Prevent popen() from displaying error on stderr

I have the following code to find the release of the Linux distribution that I am using.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
return print_osinfo();
}
int print_osinfo()
{
FILE *fp;
extern FILE* popen();
char buffer[128];
int index = 0;
memset(buffer,0,sizeof(buffer));
fp = popen("/etc/centos-release", "r");
if(!fp)
{
pclose(fp);
fp = popen("/etc/redhat-release", "r");
if(!fp)
{
pclose(fp);
return 1;
}
}
while(fgets(buffer, sizeof(buffer), fp)!= NULL)
{
printf("%s\n",buffer);
}
pclose(fp);
return 0;
}
If I run the above code on Ubuntu 14.04 I get the following error.
sh: 1: /etc/centos-release: not found
I fail to understand why it is not trying to open redhat-release and then return -1. Also, is there a way to prevent the above error from being displayed on the screen?
popen is a function more suited for accessing the output of a subprocess than for simply accessing the contents of a file. For that, you should use fopen. fopen takes a file path and a mode as arguments, so all you would need to do is replace your popens with fopens and it should work perfectly.
If you really want to use popen, it takes a shell command as it's first argument, not a filename. Try popen("cat /etc/centos-release","r"); instead.
Now, you might be a bit confused, because both of these functions return a FILE pointer. fopen returns a pointer to the file you passed as an argument. popen, however, returns a pipe pointing to the output of the command you passed to it, which C sees as a FILE pointer. This is because, in C, all i/o is file access; C's only connection to the outside world is through files. So, in order to pass the output of some shell command, popen creates what C sees as a FILE in memory, containing the output of said shell command. Since it is rather absurd to run a whole other program (the shell command) just to do what fopen does perfectly well, it makes far more sense to just use fopen to read from files that already exist on disk.

How do I read file into a command line?

Basically what I want to do is have a program with int main(argc, *argv[]) and instead of writing chars into command line, I want to have my program read those words from a file. How could I accomplish this? Is there a special command in Linux for that?
You can use standard redirect operations in a *nix shell to pass files as input:
./myprogram < inputfile.txt
This statement executes your program (myprogram) and pumps the data inside of inputfile.txt to your program
You can also redirect the output of program to a file in a similar fashion:
./myprogram > outputfile.txt
Instead of doing
for(int i = 1; i < argc; i++)
{
insert(&trie, argv[i]);
}
you could doing something like
FILE *input;
char *line;
....
while (fscanf(input, "%ms", &line) != EOF) {
insert(&trie, line);
/* If you make a copy of line in `insert()`, you should
* free `line` at here; if you do not, free it later. */
free(line);
}
Use redirection
yourprogram < youtextfile
will offer the content of yourtextfile as standard input (stdin) to yourprogram. Likewise
yourprogram > yourothertextfile
will send everything the program writes to standard output (stdout) to yourothertextfile
You'll notice when reading man pages that most system calls have a version that works directly with stdin or stdout
For example consider the printf family:
printf ("hello world\n");
is a shorter version of
fprintf (stdout,"hello world\n");
and the same goes for scanf and stdin.
This is only the most basic usage of redirection, which in my opinion is one of the key aspects of "the unix way of doing things". As such, you'll find lots of articles and tutorials that show examples that are a lot more advanced than what I wrote here. Have a look at this Linux Documentation Project page on redirection to get started.
EDIT: getting fed input via redirection ior interactively "looks" the same to the program, so it will react the same to redirected input as it does to console input. This means that if your program expects data line-wise (eg because it uses gets() to read lines), the input text file should be organized in lines.
By default, every program you execute on POSIX-compliant systems has three file descriptors open (see <unistd.h> for the macros' definition): the standard input (STDOUT_FILENO), the standard output (STDOUT_FILENO), and the error output (STDERR_FILENO), which is tied to the console.
Since you said you want read lines, I believe the ssize_t getline(char **lineptr, size_t *n, FILE *stream) function can do the job. It takes a stream (FILE pointer) as a third argument, so you must either use fopen(3) to open a file, or a combination of open(2) and fdopen(3).
Getting inspiration from man 3 getline, here is a program demonstrating what you want:
#define _GNU_SOURCE
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
size_t len;
char *line;
ssize_t bytes_read;
len = 0;
line = NULL;
if (argc > 1)
{
fp = fopen(argv[1], "r");
if (fp == NULL)
{
perror(*argv);
exit(EXIT_FAILURE);
}
}
else
fp = stdin;
while ((bytes_read = getline(&line, &len, fp)) != -1)
printf("[%2zi] %s", bytes_read, line);
free(line);
exit(EXIT_SUCCESS);
}
Without arguments, this program reads lines from the standard input: you can either feed it lines like echo "This is a line of 31 characters" | ./a.out or execute it directly and write your input from there (finish with ^D).
With a file as an argument, it will output every line from the file, and then exit.
You can have your executable read its arguments on the command line and use xargs, the special Linux command for passing the contents of a file to a command as arguments.
An alternative to xargs is parallel.

How to redirect the output of system() to a file?

In this C program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int file = open("Result", O_CREAT|O_WRONLY, S_IRWXU);
dup2(stdout, file);
system("ls -l");
return 0;
}
I'm trying to redirect the output of system() to a file, for that i have used dup2 but it is not working.
What's wrong with this code?
and, please tell me if there is any better way to do this? (without using > at the terminal )
stdout is a FILE * pointer of the standard output stream. dup2 expects file descriptor, also you've messed up the parameters order.
Use
dup2(file, 1);
instead.
On the better-way-to-do-this part. This way is bad because you probably want to restore your standard output after this system call completes. You can do this in a variety of ways. You can dup it somewhere and then dup2 it back (and close the dupped one). I personally don't like writing own cat implementations as suggested in other answers. If the only thing you want is redirecting a single shell command with system to a file in the filesystem, then probably the most direct and simple way is to construct the shell command to do this like
system("ls -l > Result");
But you have to be careful if filename (Result) comes from user input as user can supply something like 'Result; rm -rf /*' as the filename.
Also, on the topic of security, you should consider specifying the full path to ls as suggested in the comments:
system("/bin/ls -l > Result");
The simple thing is to use > indeed:
#include <stdio.h>
int main()
{
system("ls -l > /some/file");
return 0;
}
An alternative is using popen(), something along the lines of
#include <stdio.h>
#include <stdlib.h>
main()
{
char *cmd = "ls -l";
char buf[BUFSIZ];
FILE *ptr, *file;
file = fopen("/some/file", "w");
if (!file) abort();
if ((ptr = popen(cmd, "r")) != NULL) {
while (fgets(buf, BUFSIZ, ptr) != NULL)
fprintf(file, "%s", buf);
pclose(ptr);
}
fclose(file);
return 0;
}
You should use the popen() library function and read chunks of data from the returned FILE * and write them to whatever output file you like.
Reference.
use dup instead of dup2. dup creates a alias file descriptor, which value should be always the smallest available file descriptor.
new_fd = dup(file); - In this statement file might be having the value 3 (because stdin is 0, stdout is 1 and stderr is 2). so new_fd will be 4
If you want to redirect stdout into file. Then do as below.
close(stdout);
new_fd = dup(file);
Now dup will return 1 as the alias for the file descriptor, because we closed stdout so opened file descriptors are 0,2,3 and 1 is smallest available file descriptor.
If you are using dup2 means, dup2(file,1); - do like this

Read text into C. Get a bad exec error

Trying to learn C. Want to read the first line of a text file, my code is:
#include <stdio.h>
int main()
{
FILE *in = fopen("test.txt", "rt");
// read the first line from the file
char buffer[100];
fgets(buffer, 20, in);
printf("first line of \"test.txt\": %s\n", buffer);
fclose(in);
return 0;
}
I'm doing this in xCode. I get a exc bad access error.
test.txt definitely exists. It has one line that says "this is a text file"
try this after fopen() call:
if(in == NULL){
printf("Can't read teste.txt because: %s.\n", strerror(errno));
return 1;
}
and add the headers:
#include <errno.h>
#include <string.h>
The code looks fine, so my guess is that the program is not run in the same working directory as the file. Try placing the file in, say, /tmp/test.txt and use absolute path in fopen.
You don't check if the FILE is NULL. It may not be opened for a several reasons.

How to read text lines in C

I need to get lines from a text file. I already know that the lines won't be longer than 70 chars.
I have an idea about how to do it, but I'm looking a standard solution.
Maybe something like this ?
char line[MAXLEN];
while(fgets(line, sizeof(line), fp)) {
/* Do something with line. */
}
Don't forget that if you're reading in a file you need to have a file pointer and indicate what you want to do with the file. i.e. r -> read, w-> write. So it looks like you want to read the file.
So.....
Usage: gcc read.c -o read
"read input.txt"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[] ){
FILE *fp;
char buffer[70];
fp = fopen(argv[1], "r");
while(fgets(buffer,70,fp) != NULL){
puts(buffer);
}
fclose(fp);
}
This takes in the file input.txt from the command line, puts it in the char buffer, prints it, and repeats until end of file.
Cheers

Resources