tags:

views:

70

answers:

4

Hi,
How to read command line inputs using a C program.
by command line inputs, I don't mean command line arguments!!

example: * I have a text file 'inputfile.txt' with few lines of names.
* Assume my program name is names.exe.
* I have to run the program using windows command line using following command:
c:>names.exe < inputfile.txt

Thanks.

+4  A: 

Read from the stdin FILE*.

Ignacio Vazquez-Abrams
I think to read from file, I have to use the file name as an argument. But the way I have described is different. The command line sends the content of the file to the names.exe program.
Shamal Karunarathne
I think you need to reread what I wrote.
Ignacio Vazquez-Abrams
May be you are right, but I understood the idea from Jerry Coffin's answer. Thanks.
Shamal Karunarathne
A: 

For your example, the input is going to come on the standard input. Just use fread or fgets.

Carl Norum
Thanks, I'm going to try.
Shamal Karunarathne
+2  A: 

That's redirecting standard input, so in your program you don't do anything special at all -- you just read from standard input and write to standard output. If the user has redirected those, so be it.

Jerry Coffin
Thanks Jerry. Your answer made me realize what to do.
Shamal Karunarathne
I just used scanf, or gets. That was what I want.
Shamal Karunarathne
Believe me, `gets` is *not* what you want -- ever. `scanf` is fine with some care, but even when you're reading from standard input, you want to use `fgets` instead of `gets` -- along with letting you specify a file, it lets you specify the size of buffer you're reading into. Using `gets`, you have no way to limit the data to the amount of space you allocated.
Jerry Coffin
A: 

That instructs the system to replace your stdin file descriptor with a file descriptor to inputfile.txt. So just read from stdin like normal.

krousey