Reputation: 19
steps:
./inputFileName < file
How can I print the name of the file in my C program that I have typed in the terminal as an input redirection file?
Upvotes: 0
Views: 84
Reputation: 2188
If input comes from a pipe, there can't be an associated filename. Also if the file has been deleted or moved before closing the file descriptor, there is no associated filename. A file can have multiple names. In that case there are multiple filenames.
Given that, the "associated filename" of a file descriptor doesn't really make much sense. And even if you could get that info, using the filename in any way might make race conditions an issue.
The linux kernel does try to track an associated filename if a file descriptor was created by opening a file. But the keyword here is "tries".
If you are running Linux, you can find the filenname for standard input as a symlink under "/proc/self/fd/0"
. Just remember that you should not rely on that name for anything more than debug or display purposes.
Upvotes: 0
Reputation: 8354
Input redirection can be achieved not only with the '<' symbol, but also with '|'.
program < filename
is equivalent to
cat filename | program
From there, one could go to
cat file1 file2 file3 | program
You begin to see why the initial 'stdin' for an executable cannot and does not have a "filename" associated with it.
Upvotes: 0
Reputation: 36581
The input redirection is a function of the shell. Your inputFileName
executable see this as standard input. Depending on the exact operating system, you may be able to use system-specific functions to get the information you want, but there is not a standard means of doing so.
Upvotes: 1