I have a c process that waits for a scanf()
input.
I want to save its results to a *.txt
file.
To terminal (linux)
./process > out.txt
What's the way to write in terminal the scanf prehand?
Thanks.
I have a c process that waits for a scanf()
input.
I want to save its results to a *.txt
file.
To terminal (linux)
./process > out.txt
What's the way to write in terminal the scanf prehand?
Thanks.
For the below program you could give the input as.
#include <stdio.h>
int main ()
{
int i = 0;
scanf("%d", &i);
printf("Value of i = %d\n", i);
return 0;
}
$ gcc -o exe file.c
$ echo 2 | ./exe
Value of i = 2
|
or pipeline
connects two commands together so that the output from one program becomes the input of the next program.
Update:
If you want to read string, or strings and ints together
int i = 0;
char str[20];
scanf("%d%s", &i, str);
printf("Value of i = %d\nValue of str = %s\n", i, str);
$ echo "45 John" | ./exe # Ensure your input sequence is correct #
Value of i = 45
Value of str = John
For saving the output to file output.txt
$ echo "45 John" | ./exe > output.txt
$ cat output.txt
Value of i = 45
Value of str = John
You can give the input like following.
One is piping,
cat filename | ./process > sample.txt
Or else you can give like this
./process < filename > sample.txt
Or else
echo "1" | ./process > sample.txt
In that file, you can only place the integer value and gave like this.
One way of doing this is to write your scanf() input into a text file. Your input text file should be properly formatted according to scanf() sequence. Then redirect your input text file to program binary and redirect shell output of program binary to output file.
Use following command to execute your binary.
./main < input.txt > output.txt
For example:
If your main.c looks as follows
scanf("%s\n", &my_string);
scanf("%d\n", &my_int);
Then you should prepare an input.txt as follows
Hello
31
#include <stdio.h>
int main ()
{
int i = 0;
printf("Enter value of i:");
scanf("%d", &i);
printf("Value of i = %d\n", i);
return 0;
}
if I want to give dynamic input value of i. how to give it?
in the following code static value is given by echo.
$ gcc -o exe file.c
$ echo 2 | ./exe
Value of i = 2
it should display printf statement in file and from that file I should be able to give input instead of terminal.