So I need to write a code with this compilation flags:
gcc -ansi -pedantic -Wall
All on Linux based OS. The output program should print its own source code. If I change the output file name AND there is a C file with the same name in the folder it would print its content.
Up until now I managed to pull this:
#include <stdio.h>
int main()
{
char c;
FILE *my_file = fopen(__FILE__, "r");
while (c != EOF)
{
c = fgetc(my_file);
putchar(c);
}
fclose(my_file);
return 0;
}
But if I change the file name and the C file name it gives me an error. Example: For files: prnt.c, prnt
Consule -> os/23$ ./prnt
#include <stdio.h>
int main()
{
char c;
FILE *my_file = fopen(__FILE__, "r");
while (c != EOF)
{
c = fgetc(my_file);
putchar(c);
}
fclose(my_file);
return 0;
}
for same file after I change the name to test.c, test (with out compilation)
/os/23$ ./test
Segmentation fault (core dumped)
It is happening because of the __ FILE __ macro, it changes after compilation to the original file name. The question is how do I solve this problem?
int c;... then check the return value offopen(): ieif (my_file == NULL) { perror(__FILE__); exit(EXIT_FAILURE); }argv[0]for the name the binary was executed as on the command line.__FILE__.while (c != EOF)is undefined behaviour, by the way, ascis not initialised! You might initialise to~EOFto make assure it being different from. And it should be of typeintto guarantee a byte0xffreally differ from EOF (apparently yourcharis signed anyway, otherwise you'd end up in an endless loop!).