This code opens the source code file itself using the fopen()
function and reads its contents character by character using the getc()
function, and then prints each character to the console using the putchar()
function.
#include <stdio.h>
int main()
{
FILE *file_pointer;
char some_char;
file_pointer = fopen(__FILE__, "r");
while (some_char != EOF)
{
some_char = getc(file_pointer);
putchar(some_char);
}
fclose(file_pointer);
return 0;
}
Result:
#include <stdio.h>
int main()
{
FILE *file_pointer;
char some_char;
file_pointer = fopen(__FILE__, "r");
while (some_char != EOF)
{
some_char = getc(file_pointer);
putchar(some_char);
}
fclose(file_pointer);
return 0;
}
Process returned 0 (0x0) execution time : 0.031 s
Press any key to continue.
Here is a line-by-line explanation:
#include <stdio.h>
This line includes the standard input/output library.
int main()
{
This line declares the main function, which is the entry point of the program.
FILE *file_pointer;
char some_char;
This declares a file pointer file_pointer
of type FILE
, and a variable some_char
of type char
.
file_pointer = fopen(__FILE__, "r");
This line opens the current source code file (__FILE__
) in read-only mode ("r"
) and assigns the resulting file pointer to file_pointer
.
while (some_char != EOF)
{
some_char = getc(file_pointer);
putchar(some_char);
}
This block of code loops through the file pointed to by file_pointer
until the end of the file (EOF
) is reached. Each character of the file is read and assigned to some_char
using getc()
, and then printed to the console using putchar()
.
fclose(file_pointer);
This line closes the file pointed to by file_pointer
.
return 0;
}
This line signals the end of the main function and returns 0 to indicate successful program execution.
No comments:
Post a Comment