Echo Current Filename?

Is there a way to capture the name of the file being executed and save it into a string. For instance if I compile test.cpp into test.exe, I want to get the "text" portion and save it as a string. If I can figure otu how to capture the name I can take care of the truncation of the .exe portion.
The name of the program being run is passed into main.

1
2
3
4
int main ( int argc, char *argv[] )
{
  cout << "File is " << argv[0];
}
Duh! I totally forgot about argv[0]!
Thanks for your help,
Chris
technicality note:

argv[0] is not necessarily the name of the program, it is just the first value put on the commandline. It may contain other garbage. If your program is named "prog.exe", possible values for argv[0] might be:


1
2
3
4
prog
prog.exe
.\prog.exe
C:\mypath\foo\bar\..\..\baz\.\prog.exe


etc..
You could also use the __FILE__ macro which gives you the name of the file containing the code.

file.h:
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef file_h
#define file_h

#include <iostream>
using namespace std;

inline void dumpFileName()
{
	cout << "Current File is " << __FILE__ << endl;
}

#endif 


file.cpp
1
2
3
4
5
6
#include "file.h"

int main()
{
	dumpFileName();
}


Running this program results in
Current File is file.h
The __FILE__ macro is for the name of the file currently being compiled. (If that is what the OP wants.)

Obtaining the name of the file associated with the current process is a trickier subject. (See, there might not actually be a file associated with the currently executing code...)

On Windows, you can use GetModuleFilename() API function.
http://www.google.com/search?btnI=1&q=msdn+GetModuleFileName

On Linux systems, read the "proc/PID/exe" (replace PID with your process's PID) or "proc/self/exe" link, using the readlink() API function (#include <unistd.h>; 'self' is less portable than using the PID)
http://linux.die.net/man/2/readlink
http://linux.die.net/man/3/getpid

On other systems, you may be out of luck, and have to try to figure out the path from argv[0] yourself (which is a messier trick than the above options).

This should get you started. Good luck!
Topic archived. No new replies allowed.