Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C how do I print filename of file that is redirected as input in shell

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

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

like image 719
Nullpoet Avatar asked Nov 14 '09 13:11

Nullpoet


1 Answers

You can't get the filename exactly as input; the shell will handle all that redirection stuff without telling you.

In the case of a direct < file redirection, you can retrieve a filepath associated with stdin by using fstat to get an inode number for it then walking the file hierarchy similarly to find / -inum to get a path that matches it. (There might be more than one such filepath due to links.)

But you shouldn't ever need to do this. As others have said, if you need to know filenames you should be taking filenames as arguments.

like image 138
bobince Avatar answered Nov 15 '22 00:11

bobince