Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program to find current file name

Tags:

c

file

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?

like image 747
Gomathi Avatar asked Dec 16 '12 05:12

Gomathi


2 Answers

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++
like image 66
Jonathon Reinhart Avatar answered Nov 13 '22 03:11

Jonathon Reinhart


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.

like image 1
Some programmer dude Avatar answered Nov 13 '22 02:11

Some programmer dude