I have questions
How can I get the name of the "input.txt" file in the program using
./a.out < input.txt
The file name is not in the main function arguments.
I have questions
How can I get the name of the "input.txt" file in the program using
./a.out < input.txt
The file name is not in the main function arguments.
Judging by the fact that your executable is called a.out
, this is taking place under a Unix-like OS. Assuming it's Linux, while your process is running, there will be a symlink to the input file (input.txt in your case) under /proc/self/fd/0
. You can use readlink
to get the contents:
char LinkTarget[200];
readlink("/proc/self/fd/0", LinkTarget, sizeof LinkTarget);
That said, if you need the name of the file and not just the contents, you'll be better off having your program accept the file name via a command line argument (argv
internally), like Eddymage is suggesting.
In general you can't. Redirection "anonymizes" the filename. The command line interpreter (but that could be any kind of environment) usually opens the file and "transmit" the open file descriptor to the command process. Thus that process only knows the descriptor not how it was obtained.
Depending on the hosting OS it may be possible to retrieve the filename but there is no guaranty. For example, on Unixes or derivates you may retrieve it through a call to fstat
on descriptor 0, and search in the file system for (inode,idev), but even in that case, the filename may disappeared in the meantime! There are some tricks on Unixes that supports /proc
but again the filename may disappeared! On Unixes the redirection may not come from a file (see "here document" operator of shells). More usual is the input given from an anonymous pipe. Thus if redirection has been used, retrieving the "original" file is either impossible by nature, or very difficult if possible.