Views
Saving the output of a C program in a text file(Linux/Unix)
- 0 Comments
Welcome to my blog :-) .If you're new here, you may want to subscribe to my full RSS feed. Thanks for visiting!
Consider the following c program
1 2 3 4 5 6 7 8 9 10 | #include<stdio.h> main() { int i,n; printf("Enter limit\n"); scanf("%d",&n); printf("I will print %d times\n",n); for(i=0;i<n;i++) printf("I luv C\n"); } |
the output will be
Enter limit
4
I will print 4 times
I luv C
I luv C
I luv C
I luv C
This is a simple program which will print “I luv C” n times.Now, wouldn’t be nice if we saved the output in a text file
then in such case you have to use directed symbol “>>”
Usage:
./a.out >> filename.txt
let the filename for the above c program be adi.c.In order to direct the output of this program to a text file.Issue commands
bash-2.05b$ cc adi.c
bash-2.05b$ ./a.out >> adi.txt
where adi.txt is the text file in which you want to save the output
When you type ./a.out >> adi.txt and press enter ,nothing will be displayed.
Now type 5 and press enter.
Open adi.txt file by issuing command vi adi.txt
bash-2.05b$vi adi.txt
the following will be it’s contents
Enter limit
I will print 5 times
I luv C
I luv C
I luv C
I luv C
I luv C
when you direct the output to a text file,2 things are important
1.Only scanning takes place in the terminal.Means no output will be there.You have to remember the sequence in which you should enter values.
2.Your input is not saved in the text file as you can see ,the file contains “Enter limit” but doesn’t contain what i inputted.
1.If the text file already exists,then the output will be appended(added) to the existing contents
2.The text file is saved under the same directory.If you want to store it some other place then give the path
ex:
bash-2.05b$ ./a.out >> \home\adithya\output\adi.txt
will save the output to a text file named adi.txt saved in \home\adithya\output\ directory[/B]
Tip:
if you want the contents of the textfile to be of natural output ,then after every scanf() statement issue appropriate printf() statement of the value you scanned.
Ex:if you want to make the directed output file of the above program match exatly with real output then make this change
printf("Enter limit\n");
scanf("%d",&n);
printf("%d\n",n);
now the contents of the text file will be like this
Enter limit
5
I will print 5 times
I luv C
I luv C
I luv C
I luv C
I luv C
![]()








