I would like to display my current C file using C program. I know that the executable name can be obtained by argv[0]
. But I want the file name as 'hello.c'
for example. Is it possible?
A single program can be comprised of several C files. So which one are you looking for?
The __FILE__
macro was made for this reason. It is replaced by the preprocessor with the name of the current source (.C) file being compiled.
main.c
#include <stdio.h>
int main(int argc, char** argv)
{
printf("Executable name: %s\n", argv[0]);
printf("This is %s() from %s, line %d\n",
__FUNCTION__, __FILE__, __LINE__);
one();
return 0;
}
one.c
#include <stdio.h>
void one(void)
{
printf("This is %s() from %s, line %d\n",
__FUNCTION__, __FILE__, __LINE__);
}
Output (assuming executable name is "hello.exe"):
Executable name: hello.exe
This is main() from main.c, line 4
This is one() from one.c, line 3
See also:
__FILE__
, __LINE__
, and __FUNCTION__
usage in C++If you're on Windows, and have the ".exe"
extension to your program, then replace that extension with ".c"
. If you're on Linux or OSX, then just append ".c"
, but do not append directly to argv[0]
as that string won't have space allocated for that. Create a new string instead.
This will however not work in all situations, as the actual source file and executable may of course by named differently, and the executable may not even be in the same folder as the source file. Getting the actual name of the source file can be done with the __FILE__
macro. If you are using VisualC++ then you can add a flag to the compiler telling it to use full path in the __FILE__
macro, see this MSDN reference. The GCC pre-processor already have the full path in __FILE__
, see the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With