I am questioning my solution to the last exercise in Accelerated C++:
Write a self-reproducing program. Such a program is one that does no input, and that, when run, writes a copy of its own source text on the standard output stream.
My solution:
using std::string;
using std::cout;
using std::endl;
using std::ifstream;
using std::getline;
void selfReproduce16_1()
{
ifstream thisFile("C:\\Users\\Kevin\\Documents\\NetBeansProjects\\Accelerated_C++_Exercises\\Chapter_16.cpp", ifstream::in);
string curLine;
bool foundHeader = false;
while(getline(thisFile, curLine))
{
if(!curLine.compare("void selfReproduce16_1()") || foundHeader)
{
foundHeader = true;
cout << curLine << endl;
}
}
}
This only prints out the source text of the solution (this function). Is this the solution that they had in mind?
I would like a dynamic solution that does not require hard-coding the location of the source file. However, I am not aware of a way to get the location of a source file automatically during runtime.
Another point related to that is the inclusion of "included" files, and (when encountering a function call), automatically obtaining the location of the source file that the function is stored in. To me, this would be a true "self-reproducing" program.
Is this possible in C++? If so, how?
A program that prints itself is called Quine.
I think your solution wouldn't be considered valid: quines usually aren't allowed to read files (nor to get any other kind of input). It's possible to writ a Quine C++ program, here you could find many quine implementations in several languages.