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

后端 未结 9 1689
情深已故
情深已故 2020-12-10 17:35
$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条回答
  • 2020-12-10 18:14

    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.

    0 讨论(0)
  • 2020-12-10 18:17

    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

    0 讨论(0)
  • 2020-12-10 18:21

    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.

    0 讨论(0)
  • 2020-12-10 18:22

    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.

    0 讨论(0)
  • 2020-12-10 18:24

    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.

    0 讨论(0)
  • 2020-12-10 18:25

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

    0 讨论(0)
提交回复
热议问题