Nagireddy Sai Sunhith
Nagireddy Sai Sunhith

Reputation: 19

how to get the file name in C program, that i had given in input redirection?

steps:

  1. Let's say I have a C program inputFileName.c
  2. I run inputFileName with input redirection such as ./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

Answers (3)

HAL9000
HAL9000

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

Fe2O3
Fe2O3

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

Chris
Chris

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

Related Questions