top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Print source code using C program

+3 votes
1,059 views

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

posted Oct 31, 2013 by anonymous

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

5 Answers

+1 vote

See this if it is helpful

#include <stdio.h>
char *program = "#include <stdio.h>%cchar *program = %c%s%c;%cint main()%c{%cprintf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);%c    return 0;%c}%c";
//what is this line doing, what is the use of %c and %s and what properties of %c and %s are being used here?
int main()
{
        printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);
        //what is this print function doing, and how?
        return 0;
}

10 is newline
34 id "
Basically you rewrite the whole program in the program variable with 10 as newline and 34 as "....Rest is self explanatory.

answer Oct 31, 2013 by Salil Agrawal
Nice.

But will this work for all ?  what happens if i include one more line in this program, will this print all the lines without any change in your program ?
Some work to be done but its one of the way
+1 vote

To make it generic you can use the __FILE__ macro so that it will take the current program's file and print the file content as output after reading.

answer Nov 1, 2013 by Sachidananda Sahu
0 votes

It is possible through file handling. Save your program as Text.c and read it through your C code.

answer Oct 31, 2013 by sivanraj
That may not be the purpose of the problem (myview) probably user is looking for some way by which he can print the program which he is executing.
agree salil. let here it from owner.
0 votes

It may be possible if you use file concepts to print the source code in your program....

Just read the saved program using file read command and them print it on the screen....
By this you could be able to print the source code..

answer Oct 31, 2013 by anonymous
0 votes

Try this,

#include <stdio.h>

int main(int argc,char *argv[])
{
    char buf[100];
    if(argc != 2){
        printf("usage : exe <filename>\n");
        sprintf(buf,"cat %s",__FILE__);
    }else{
    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

+1 vote

How to create a c program to print a alphabet in the form of stars for ex.
A should be printed something like

   *
  * *
 *****
*     *

Do we have any standard algo???

+1 vote

Code should compile and print out itself.

...