Exercise:
Write a C Program to display its own source code as output.
Click Here to View the Solution!
#include <stdio.h>
int main() {
FILE *fp;
int c;
// open the current input file
fp = fopen(__FILE__,"r");
do {
c = getc(fp);
putchar(c);
}
while(c != EOF); // loop until the end of file is reached
fclose(fp);
return 0;
}
Click Here to View the Output!
/
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*/
include
int main() {
FILE *fp;
int c;
// open the current input file
fp = fopen(FILE,"r");
do {
c = getc(fp);
putchar(c);
}
while(c != EOF); // loop until the end of file is reached
fclose(fp);
return 0;
}
Click Here to View the Explanation!
- This program is used to display its own source code as the program’s output.
- In
main()
, afile pointer *fp
and an integer variablec
is created. - The current open input file is opened using a predefined macro of the name
__FILE__
inside thefopen function
and the reading mode as its parameters. - A
do while loop
is set which first reads the character in the file usinggetc
and stores in the variablec
and then displays the character usingputchar
. - The
while loop
is initialized which will continue its iterations until the end of the file is reached. - Finally, the file is closed using the
fclose() function
.