I am doing some basic file manipulations, and would like to store the name the file passed to an executable C program and create a new file that has an extension tacked on the original filename. For example, if this were what I typed on the command line:
a.out < some_file.txt
Where a.out is an executable, is there a way to get the string some_file.txt, so I could open up a new file and call it some_file.text.mod or something else?
argv[0] gets you a.out, and in scripting you could use $1 to access arguments (but not the filenames used in redirection), but neither of those is much use here.
Any ideas?
Sometime (and almost always in practice)
/proc/self/fd/0could be a symbolic link to the file. (But the symlink could be crappy, e.g. for a pipe, and this is Linux specific).So from inside your
a.outyou could call thereadlink(2)system call on/proc/self/fd/0But doing that is a bit disgusting. However it works:
Again, it is highly Linux specific and not portable to other Posix systems.