Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

benthicwhale

macrumors newbie
Original poster
Jul 30, 2011
10
0
Hi, guys. I have a simple question, please help me.

I am learning C program now with emacs and command line. I know that after gcc compiling the .c file. We can use a.out in command line to execute the file and get the result. While we can add some arguments behind a.out for different purpose of input.

For example, we can use a.out < input1.txt.

My question is if there is a argument transferred from a.out. Which parameter should I use to receive this argument? *argv of main()? And how can I open input1.txt in my C program?

Thank you very much.
 
The syntax you've shown is used to redirect the file input1.txt to STDIN, a special file/device used to accept input into your program. Normally this will be attached to your console so you can type input into your program. To read the contents of the file when it is delivered to your program you would read from STDIN until you see the EOF or end of file character. There are a number of functions you can use to read STDIN such as fgets.

The arguments that main accepts are for command line parameters:
a.out argA argB
Would result in argc being set to 3, and argv would contain:
argv[0] -> "a.out"
argv[1] -> "argA"
argv[2] -> "argB"

This allows you to alter your program's behavior based on these command line arguments.

Where are you learning from? Where did you see the redirection of a file using <? Was there no example of how to use this in your program where you found it?

-Lee
 
I suggest writing a program that prints the values received by main in argv, one per line, numbered. It will help you understand how argc and argv work.

It's also a useful tool, because it can show you how things like quoting and shell-variable expansion work.

When you run the program as:
Code:
a.out <input1.txt
you should discover that input1.txt is not present in argv. That's because the shell (or emacs, or whatever runs a.out) has redirected the stdin stream to input1.txt.
http://en.wikipedia.org/wiki/Redirection_(computing)

Quoting will PREVENT redirection. Examples:
Code:
a.out "<input1.txt"
a.out "<" input1.txt
a.out "<"input1.txt
 
Thank you guys.
But I am still a confused. If using a.out < 1.txt and '1.txt' will not present in argv, then how can I use the data of stream for 1.txt in my main.c?

Thank you very much!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.