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条回答
甜甜的少女心
2楼-- · 2020-02-06 02:48

Why do you want to do this? All your program a.out is passed from the shell, is an open file descriptor, stdin.

The user might as well do this:

cat inpfilename | ./a.out

and now you have absolutely no filename to use (except /dev/stdin).

If a.out needs to work with filenames, why not take the file as a command-line argument?

查看更多
Root(大扎)
3楼-- · 2020-02-06 02:50

Only the parent shell is going to know that. The program, a.out is always going to see it as stdin.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-02-06 02:50

As you put it the process that runs a.out has no notion of the file name of the file that provides its' standard input.

The invocation should be:

$ ./a.out inputfilename

and parse argv in int main( int argc, char* argv[] ) { ... }

or

$ ./a.out <<< "inputfilename"

And get the filename from stdin.

Then in a.c you need to fopen that file to read it's content.

查看更多
欢心
5楼-- · 2020-02-06 02:50

An fstat(0,sb) (0 is stdin file descriptor) will give you details on the input file, size, permissions (called mode) and inode of the device it resides on.

Anyway you won't be able to tell its path: as unix inodes have no idea what path they belong to, and technically (see ln) they could belong to more than one path.

查看更多
神经病院院长
6楼-- · 2020-02-06 02:52

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.

查看更多
\"骚年 ilove
7楼-- · 2020-02-06 02:53

In fact, it is possible to get filename from procfs, since /proc/*/fd contains symlink to opened files:

char filename[bufsize];
int sz = readlink("/proc/self/fd/0", filename, bufsize-1);
filename[sz] = 0;
puts(filename);
查看更多
登录 后发表回答