C/C++ program that prints its own source code as its output - c

Wikipedia says it's called a quine and someone gave the code below:
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}
But, obviously you have to add
#include <stdio.h> //corrected from #include <stdlib.h>
so that the printf() could work.
Literally, since the above program did not print #include <stdio.h>, it is not a solution (?)
I am confused about the literal requirement of "print its own source code", and any purpose of this kind of problems, especially at interviews.

The main purpose of interview questions about quine programs is usually to see whether you've come across them before. They are almost never useful in any other sense.
The code above can be upgraded modestly to make a C99-compliant program (according to GCC), as follows:
Compilation
/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes \
-Wstrict-prototypes -Wold-style-definition quine.c -o quine
Code
#include <stdio.h>
char*s="#include <stdio.h>%cchar*s=%c%s%c;%cint main(void){printf(s,10,34,s,34,10,10);}%c";
int main(void){printf(s,10,34,s,34,10,10);}
Note that this assumes a code set where " is code point 34 and newline is code point 10. This version prints out a newline at the end, unlike the original. It also contains the #include <stdio.h> that is needed, and the lines are almost short enough to work on SO without a horizontal scroll bar. With a little more effort, it could undoubtedly be made short enough.
Test
The acid test for the quine program is:
./quine | diff quine.c -
If there's a difference between the source code and the output, it will be reported.
An almost useful application of "quine-like" techniques
Way back in the days of my youth, I produced a bilingual "self-reproducing" program. It was a combination of shell script and Informix-4GL (I4GL) source code. One property that made this possible was that I4GL treats { ... } as a comment, but the shell treats that as a unit of I/O redirection. I4GL also has #...EOL comments, as does the shell. The shell script at the top of the file included data and operations to regenerate the complex sequence of validation operations in a language that does not support pointers. The data controlled which I4GL functions we generated and how each one was generated. The I4GL code was then compiled to validate the data imported from an external data source on a weekly basis.
If you ran the file (call it file0.4gl) as a shell script and captured the output (call that file1.4gl), and then ran file1.4gl as a shell script and captured the output in file2.4gl, the two files file1.4gl and file2.4gl would be identical. However, file0.4gl could be missing all the generated I4GL code and as long as the shell script 'comment' at the top of the file was not damaged, it would regenerate a self-replicating file.

The trick here is that most compilers will compile without requiring you to include stdio.h.
They will usually just throw a warning.

A quine has some depth roots in fixed point semantics related to programming languages and to executions in general. They have some importance related to theoretical computer science but in practice they have no purpose.
They are a sort of challenge or tricks.
The literal requirement is just you said, literal: you have a program, its execution produces itself as the output. Nothing more nor less, that's why it's considered a fixed point: the execution of the program through the language semantics has itself as its ouput.
So if you express the computation as a function you'll have that
f(program, environment) = program
In the case of a quine the environment is considered empty (you don't have anything as input neither precomputed before)

You can also define printf's prototype by hand.
const char *a="const char *a=%c%s%c;int printf(const char*,...);int main(){printf(a,34,a,34);}";int printf(const char*,...);int main(){printf(a,34,a,34);}

Here's a version that will be accepted by C++ compilers:
#include<stdio.h>
const char*s="#include<stdio.h>%cconst char*s=%c%s%c;int main(int,char**){printf(s,10,34,s,34);return 0;}";int main(int,char**){printf(s,10,34,s,34);return 0;}
test run:
$ /usr/bin/g++ -o quine quine.cpp
$ ./quine | diff quine.cpp - && echo 'it is a quine' || echo 'it is not a quine'
it is a quine
The string s contains mostly a copy of the source, except for the content of s itself - instead it has %c%s%c there.
The trick is that in the printf call, the string s is used both as format and as the replacement for the %s. This causes printf to put it also into the definition of s (on the output text, that is)
the additional 10 and 34s correspond to the linefeed and " string delimiter. They are inserted by printf as replacements of the %cs, because they would require an additional \ in the format-string, which would cause the format- and replacement-string to differ, so the trick wouldn't work anymore.

Quine (Basic self-relicating code in c++`// Self replicating basic code
[http://www.nyx.net/~gthompso/quine.htm#links]
[https://pastebin.com/2UkGbRPF#links]
// Self replicating basic code
#include <iostream> //1 line
#include <string> //2 line
using namespace std; //3 line
//4 line
int main(int argc, char* argv[]) //5th line
{
char q = 34; //7th line
string l[] = { //8th line ---- code will pause here and will resume later in 3rd for loop
" ",
"#include <iostream> //1 line ",
"#include <string> //2 line ",
"using namespace std; //3 line ",
" //4 line ",
"int main(int argc, char* argv[]) //5th line ",
"{",
" char q = 34; //7th line ",
" string l[] = { //8th line ",
" }; //9th resume printing end part of code ", //3rd loop starts printing from here
" for(int i = 0; i < 9; i++) //10th first half code ",
" cout << l[i] << endl; //11th line",
" for(int i = 0; i < 18; i++) //12th whole code ",
" cout << l[0] + q + l[i] + q + ',' << endl; 13th line",
" for(int i = 9; i < 18; i++) //14th last part of code",
" cout << l[i] << endl; //15th line",
" return 0; //16th line",
"} //17th line",
}; //9th resume printing end part of code
for(int i = 0; i < 9; i++) //10th first half code
cout << l[i] << endl; //11th line
for(int i = 0; i < 18; i++) //12th whole code
cout << l[0] + q + l[i] + q + ',' << endl; 13th line
for(int i = 9; i < 18; i++) //14th last part of code
cout << l[i] << endl; //15th line
return 0; //16th line
} //17th line

Not sure if you were wanting the answer on how to do this. But this works:
#include <cstdio>
int main () {char n[] = R"(#include <cstdio>
int main () {char n[] = R"(%s%c"; printf(n, n, 41); })"; printf(n, n, 41); }
If you are a golfer, this is a more minified version:
#include<cstdio>
int main(){char n[]=R"(#include<cstdio>
int main(){char n[]=R"(%s%c";printf(n,n,41);})";printf(n,n,41);}

My version without using %c:
#include <stdio.h>
#define S(x) #x
#define P(x) printf(S(S(%s)),x)
int main(){char y[5][300]={
S(#include <stdio.h>),
S(#define S(x) #x),
S(#define P(x) printf(S(S(%s)),x)),
S(int main(){char y[5][300]={),
S(};puts(y[0]);puts(y[1]);puts(y[2]);puts(y[3]);P(y[0]);putchar(',');puts(S());P(y[1]);putchar(',');puts(S());P(y[2]);putchar(',');puts(S());P(y[3]);putchar(',');puts(S());P(y[4]);puts(S());fputs(y[4],stdout);})
};puts(y[0]);puts(y[1]);puts(y[2]);puts(y[3]);P(y[0]);putchar(',');puts(S());P(y[1]);putchar(',');puts(S());P(y[2]);putchar(',');puts(S());P(y[3]);putchar(',');puts(S());P(y[4]);puts(S());fputs(y[4],stdout);}

/* C/C++ code that shows its own source code without and with File line number and C/C++ code that shows its own file path name of the file. With Line numbers */
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define SHOW_SOURCE_CODE
#define SHOW_SOURCE_FILE_PATH
/// Above two lines are user defined Macros
int main(void) {
/* shows source code without File line number.
#ifdef SHOW_SOURCE_CODE
// We can append this code to any C program
// such that it prints its source code.
char c;
FILE *fp = fopen(__FILE__, "r");
do
{
c = fgetc(fp);
putchar(c);
}
while (c != EOF);
fclose(fp);
// We can append this code to any C program
// such that it prints its source code.
#endif
*/
#ifdef SHOW_SOURCE_FILE_PATH
/// Prints location of C this C code.
printf("%s \n",__FILE__);
#endif
#ifdef SHOW_SOURCE_CODE
/// We can append this code to any C program
/// such that it prints its source code with line number.
unsigned long ln = 0;
FILE *fp = fopen(__FILE__, "r");
int prev = '\n';
int c; // Use int here, not char
while((c=getc(fp))!=EOF) {
if (prev == '\n'){
printf("%05lu ", ++ln);
}
putchar(c);
prev = c;
}
if (prev != '\n') {
putchar('\n'); /// print a \n for input that lacks a final \n
}
printf("lines num: %lu\n", ln);
fclose(fp);
/// We can append this code to any C program
/// such that it prints its source code with line number.
#endif
return 0;
}

main(a){printf(a="main(a){printf(a=%c%s%c,34,a,34);}",34,a,34);}

Related

having issues with simple for loop program. the similar code is having completely different results

I am a beginner programmer. i have just started learning c++. I am currently trying to find project which will help me in practicing different types of loop and command statements. in my recent project of creating a program to find factorial for a given number using for loop i am having problems which might be due to code differences. Can you guys help me find the differences in each code and why the outputs of each program are different ?
this is a code i wrote myself :
#include <iostream>
using namespace std;
int main (){
int i,B;
// B=1;
for (i=0; i < 10; i++);
{
//B*=i;
cout << i;
//cout << B << endl;
}
}
the code above gives output of only 10
this is a code i copied
#include <iostream>
using namespace std;
int main(){
int a;
for (int a=1; a <=10;a++)
{
cout << a << endl ;
}
}
this gives output of all the numbers upto 10.
i cant see any reason why the first code would give me an output of 10 as it is "<10" and not "<=10

Strange output when using system("clear") command in C program

I have the following code
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
#define dimensions 5
int RandomNumInRange(int M, int N)
{
return M + rand() / (RAND_MAX / (N - M + 1) + 1);
}
char ** CreateWorld(int dim)
{
int i,j;
char **world = malloc(dim *sizeof(char*));
for(i=0;i<dim;i++)
world[i]=malloc(dim*sizeof(char));
for(i=0;i<dim;i++)
for(j=0;j<dim;j++)
world[i][j]=42;
return world;
}
void CreateCastle(char **world)
{
//assuming world is big enough
//to hold a match of 2
int randRow,randCol;
//1 to dimension -2 so we can spawn a 3x3 castle
randRow = RandomNumInRange(1,dimensions-2);
randCol = RandomNumInRange(1,dimensions-2);
printf("position: %d %d\n", randRow, randCol);
world[randRow][randCol]='c';
//fill the rest so castle is 3x3
//assuming there is enough space for that
world[randRow-1][randCol-1]=35;
world[randRow-1][randCol]=35;
world[randRow-1][randCol+1]=35;
world[randRow][randCol-1]=35;
world[randRow][randCol+1]=35;
world[randRow+1][randCol-1]=35;
world[randRow+1][randCol]=35;
world[randRow+1][randCol+1]=35;
}
void DisplayWorld(char** world)
{
int i,j;
for(i=0;i<dimensions;i++)
{
for(j=0;j<dimensions;j++)
{
printf("%c",world[i][j]);
}
printf("\n");
}
}
int main(void){
system("clear");
int i,j;
srand (time(NULL));
char **world = CreateWorld(dimensions);
DisplayWorld(world);
CreateCastle(world);
printf("Castle Positions:\n");
DisplayWorld(world);
//free allocated memory
free(world);
//3 star strats
char ***world1 = malloc(3 *sizeof(char**));
for(i=0;i<3;i++)
world1[i]=malloc(3*sizeof(char*));
for(i=0;i<3;i++)
for(j=0;j<3;j++)
world1[i][j]="\u254B";
for(i=0;i<3;i++){
for(j=0;j<3;j++)
printf("%s",world1[i][j]);
puts("");
}
free(world1);
//end
return 0 ;
}
If I use the system("clear") command, I get a line consisting of "[3;J"
followed by an expected output. If I run the program again, I get the same gibberish, then many blank newlines, then the expected output. If I put the system("clear") command in comments then both the "[3;J" and the blank newlines don't show and the output is expected.
Edit: it seems the error is not in the code, but rather in the way the terminal on my system is (not) set. Thank you all for your input, I definitely have a lot of interesting stuff to read and learn now.
The codes being sent by your clear command from don't seem to be compatible with the Gnome terminal emulator, which I believe is what you would be using.
The normal control codes to clear a console are CSI H CSI J. (CSI is the Control Sequence Initializer: an escape character \033 followed by a [). CSI H sends the cursor to the home position, and CSI J clears from the cursor position to the end of the screen. You could also use CSI 2 J which clears the entire screen.
On Linux consoles and some terminal emulators, you can use CSI 3 J to clear both the entire screen and the scrollback. I would consider it unfriendly to do this (and the clear command installed on my system doesn't.)
CSI sequences can typically contain semicolons to separate numeric arguments. However, the J command doesn't accept more than one numeric argument and the semicolon seems to cause Gnome terminal to fail to recognize the control sequence. In any event, I don't believe Gnome terminal supports CSI 3 J.
The clear command normally uses the terminfo database to find the correct control sequences for the terminal. It identifies the terminal by using the value of the TERM environment variable, which suggests that you have to wrong value for that variable. Try setting export TERM=xterm and see if you get different results. If that works, you'll have to figure out where Linux Mint configures environment variables and fix it.
On the whole, you shouldn't need to use system("clear") to clear your screen; it's entirely too much overhead for such a simple task. You would be better off using tputs from the ncurses package. However, that also uses the terminfo database, so you will have to fix your TERM setting in any case.

How to convert hex data to a data structure in gdb

I usually analyzing some hex dump from crash log, this hex dump belong to some very complicate data structure.
So I wander if gdb has some convenient command to translate the hexdump to data structure.
For example, I got some the hexdump 0xAAABBCCDDEEFF, is there a way to convert it back to the data structure?
for example:
p ((struct very_complcate_structure)(0xAABBCCDDEEFF)).u.flag.a
Thanks!
I got some the hexdump 0xAAABBCCDDEEFF
The trick is to get these values into memory of a running process. It may be useful to write a tiny helper program for this.
For example, suppose that you have a hex dump of a packet, and the remote server printed that packet out, then crashed. (The usual way to debug this is to make remote server dump core, and then debug that core -- this will allow you to debug many more problems than what is possible to debug using your "logging" approach, but I digress).
So we write a helper program like this (using this answer):
#include <string.h>
#include <sstream>
#include <iostream>
#include "packet.h" // "complicated" packet structure defined here.
int main(int argc, char *argv[]) {
struct packet pkt;
static const int num_ints = ((sizeof(pkt) + sizeof(int) - 1) & ~(sizeof(int) - 1)) / sizeof(int);
for (int j = 1; j < argc; j++) {
memset(&pkt, 0, sizeof(pkt)); // start in clean state
// chop input string into 8-char chunks
std::string s = argv[j];
for (int k = 0; k < num_ints && k < (s.size() / 8) + 1 ; k++) {
std::stringstream ss;
ss << std::hex << s.substr(8 * k, 8);
unsigned int x;
ss >> x;
((unsigned int *)&pkt)[k] = x;
}
std::cout << std::endl; // break here.
}
}
Now compile this program with g++ -g helper.cc -o helper, run it with
gdb -q ./helper AAABBCCDDEEFF....
Set breakpoint on line 24 (the "break here" line), and use print pkt to examine the decoded packet.

C - Message digest, same value returning every time (1 of 4 files should have a different value)

One of my files should be different than the others and this program is supposed to tell me which. I have a feeling that the "_setmode..." could be wrong (actually almost sure, it doesn't seem to have any effect - it's supposed to set input mode to binary at the start of the program). To test, I'm resetting the program after each use and renaming the text files so they are all tested with the same name. I'm using C:/Users/User/Desktop/file.txt as my DOS command.
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(void){
int s1=0, s2=0, s3=0, s4=0;
int m1=3, m2=7, m3=13, m4=23;
int B;
_setmode(_fileno(stdin), _O_BINARY);
while((B=getchar()) != EOF)
{
s1 = (s1 + B*m1) % 256;
s2 = (s1+s2 + B*m2) % 256;
s3 = (s1+s2+s3 + B*m3) % 256;
s4 = (s1+s2+s3+s4 + B*m4) % 256;
B = getchar();
printf("%02x%02x%02x%02x\n", s1, s2, s3, s4 );
}
return 0;
}
Files I'm using (pastebin with pastebin links to files since I need more rep to post more than 2 links):
File Links: http://pastebin.com/wLF9NRNu
I also just found out that I'm apparently only supposed to be checking the midpoint value, so I was given the following command, which seems more or less useless to me:
C:\ > mdPoint < file.txt
Also after playing with it some more, it seems my commands aren't opening the files at all and is just giving me output based on the command text I enter. Not sure what's up with that.
Not an answer but too much for a comment. I tested your program on three files. The first file test1.txt contains the text "one".
yourprogram < test1.txt
4d5646e2
7c95787e
An identical file test11.txt has the same content "one" and the same result.
yourprogram < test11.txt
4d5646e2
7c95787e
The next file test2.txt contains the text "two".
yourprogram < test2.txt
5c88c818
a93a4e42
So your comments about the result being "based on the command text" are incorrect, it works off the content. Perhaps you need a better thought out and presented question. And your pastebin does not contain anything easily accessible.
You had some errors in your code. I believe you mean the following:
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(void){
int s1=0, s2=0, s3=0, s4=0;
int m1=3, m2=7, m3=13, m4=23;
int B;
_setmode(_fileno(stdin), _O_BINARY);
while((B=getchar()) != EOF)
{
s1 = (s1 + B*m1) % 256;
s2 = (s1+s2 + B*m2) % 256;
s3 = (s1+s2+s3 + B*m3) % 256;
s4 = (s1+s2+s3+s4 + B*m4) % 256;
}
printf("%02x%02x%02x%02x\n", s1, s2, s3, s4 );
return 0;
}

Using gcc to compile a C program

I am following an example from CUNY and I have never done anything with C before so I probably don't know what I am doing.
Consider the program below.
Do I need a shebang line for C code written in emacs?
When I go to compile using the line gcc -g -o forwardadding forwardadding.c
I am hit with the message:
forwardadding.c:9:17: error: expected expression before ‘<’ token
Once I get the code compiles, I can use gdb to debug and run the code corrrect?
The code:
#include <stdio.h>
#include <math.h>
main()
{
float sum, term;
int i;
sum = 0.0;
for( i = 1; < 10000000; i++)
{
term = (float) i;
term = term * term;
term = 1 / term;
sum += term;
}
printf("The sum is %.12f\n", sum);
}
No shebang is needed. You could add an Emacs mode line comment.
The for loop should be:
for (i = 1; i < 10000000; i++)
Your code is missing the second i.
Yes, you can use GDB once you've got the code compiling.
You'd get a better answer to the mathematics if you counted down from 10,000,000 than by counting up to 10,000,000. After about i = 10000, the extra values add nothing to the result.
Please get into the habit of writing C99 code. That means you should write:
int main(void)
with the return type of int being required and the void being recommended.
You need to put a variable in the for loop for a complete expression (which is probably line 9...)
for( i = 1; < 10000000; i++)
change to this
for( i = 1; i < 10000000; i++)
You are missing an an i. Just correct that as Jonathan Leffler has suggested and save your file. Open your terminal and just use this to compile your code gcc your_file_name.c and your code compiles next to run the code that just compiled type ./a.out and your program runs and shows you the output.

Resources