- #1
daniel_i_l
Gold Member
- 867
- 0
Is it possible to write a program (in any language) so that the output is the code of the program itself?
Yes.Is it possible to write a program (in any language) so that the output is the code of the program itself?
It will not work - first of all, executable and the source files are different, second, files don't have to be in the same directory.int main(int argc, char* argv[])
{
string filename = argv[0];
readFile(filename);
}
it will work if u have only 1 source code file(*.cpp) and keep the exe file in the same directory. of course, u ll have to get the filename correctly.The idea (although not listed in the OP) is that the program doesn't accept any input nor doesn't read external files. Besides, you are making several faulty assumptions.
It will not work - first of all, executable and the source files are different, second, files don't have to be in the same directory.
Not only exe must be in the same directory, but both exe and cpp files have to share the same name. It won't work.it will work if u have only 1 source code file(*.cpp) and keep the exe file in the same directory. of course, u ll have to get the filename correctly.
#include <iostream> // Standard header
int main()
{
std::cout << "Hello, world!\n";
std::cout << "#include <iostream> // Standard header\n";
std::cout << "\n";
std::cout << "int main()\n";
std::cout << "{\n";
std::cout << "\n";
std::cout << "std::cout \<\< \"Hello, world!\\n\";\n";
std::cout << "}\n";
}
That's not a program producing it's source code: that's a program asking an external process for some text, and then displaying it.D'oh I just realised the solution is the method one poster above has done, just read a file and print it to screen, but just make sure that file is code itself!
#!/usr/bin/perl
use strict;
sub quote;
$string = <<"HERE";
#!/usr/bin/perl
use strict;
sub quote;
\$string = <<"HERE";
placeholder
\$quoted = quote(\$string);
\$string ~= s/^placeholder\$/\$quoted/m;
print \$string;
sub quote {
my \$s = shift;
\$s ~= s/\\\$/\\\\\\\$/sg;
\$s ~= s/\\\\/\\\\\\\\/sg;
\$s .= "\\nHERE";
return \$s;
}
HERE
$quoted = quote($string);
$string ~= s/^placeholder$/$quoted/m;
print $string;
sub quote {
my $s = shift;
$s ~= s/\$/\\\$/sg;
$s ~= s/\\/\\\\/sg;
$s .= "\nHERE";
return $s;
}