In C how do I print filename of file that is redir

2020-02-06 02:12发布

$cc a.c
$./a.out < inpfilename

I want to print inpfilename on stdout. How do I do that ? Thanks for the help in advance...

9条回答
ゆ 、 Hurt°
2楼-- · 2020-02-06 02:57

Your operating system will supply your program with input from this file. This is transparent to your program, and as such you don't get to see the name of the file. In fact, under some circumstances you will be fed input which doesn't come from a file, such as this:

ls | ./a.out

What you're after is very system-specific. Probably a better solution is to pass the filename as a parameter. That way you get the filename, and you can open it to read the content.

查看更多
贼婆χ
3楼-- · 2020-02-06 02:58

I don't think it's possible, since < just reads the contents of inpfilename to STDIN.

If you want inpfilename to be available to your program, but you also want to be able to accept data from STDIN, set up your program to accept a filename argument and fopen that to a FILE. If no argument is given assign STDIN to your FILE. Then your input reading routine uses functions like fscanf rather than scanf, and the FILE that you pass in is either a link to the fopened file or STDIN.

查看更多
何必那么认真
4楼-- · 2020-02-06 03:09

G'day,

As pointed out in the above answer all you see is the open file descriptor stdin.

If you really want to do this, you could specify that the first line of the input file must be the name of the file itself.

HTH

查看更多
登录 后发表回答