top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a program that, when run, will print out its source code?

+1 vote
703 views

Code should compile and print out itself.

posted Aug 19, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+1 vote

Assume the source code file name is "example.c", below code might help you.

#include <stdio.h>

int main()
{
    FILE *fp = NULL;
    int c;

    fp = fopen("example.c", "r");
    if (fp == NULL) {
        printf("Unable to open the source code.\n");
        return 0;
    }

    while((c = fgetc(fp)) != EOF)
        fputc(c, stderr);

    fclose(fp);
    return 0;
}
answer Aug 19, 2014 by Arshad Khan
+1 vote

Self printing program is called Quines and you can find many solution on the web, one is what Arshad has suggested another one you can find here -

#include <stdio.h>
#define d "\\"
#define c "\n"
#define b "\""
#define a "#include <stdio.h>%s#define d %s%s%s%s%s#define c %s%sn%s%s#define b %s%s%s%s%s#define a %s%s%s%smain(){printf(a,c,b,d,d,b,c,b,d,b,c,b,d,b,b,c,b,a,b,c,c);}%s"
main(){printf(a,c,b,d,d,b,c,b,d,b,c,b,d,b,b,c,b,a,b,c,c);}
answer Aug 19, 2014 by Salil Agrawal
0 votes

Try this,

#include <stdio.h>

int main(int argc,char *argv[])
{
    if(argc != 2){
        printf("usage : exe <filename>\n");
        return 0;
    }
    char buf[100];
    sprintf(buf,"cat %s",argv[1]);
    system(buf);
    return 0;
} 
answer Nov 27, 2014 by Bheemappa G
Similar Questions
+2 votes

Hello friends I am searching the Program to print source code as program output in C programming

+2 votes

Input:
arr = {'a', 'b'}, length = 3

Output:
aaa
aab
aba
abb
baa
bab
bba
bbb

+3 votes

How to write a program in C or C++ which can print its source code on execution.

+1 vote

Instead of running on executable , i want to run on source code .... is it possible with valgrind or not ... please help how i can i run on source code ?

If not possible suggest me some alternate ways...

...