ale-batt ale-batt - 1 year ago 79
C Question

Quine create and execute file

I am creating a Quine in C and where i need to create a new c file and then compile it and execute it.

I made a simple snippet to understand why it's not working.

My guess is that

start the command before fprintf is done writing but i put a sleep and it's wasn't working too.

(All my apologize for this ugliest code but it's not the goal)

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main()
char *cmd[100]= {"sh", "-c", "\"gcc tmp.c && ./a.out\""};

fprintf(fopen("tmp.c", "w"), "#include <stdio.h>\nint main(){puts(\"Hello World\");}");
execv("/bin/sh", cmd);
return (0);


sh: gcc tmp.c && ./a.out: No such file or directory

Any idea ?

usr usr
Answer Source

Your argument array cmd is not terminated with a NULL pointer. Also, it has the quote issue.

You should also close the file before execv() call. The reason you are not seeing anything in the file is because fprintf() buffering. While all the open files are closed at process exit, you are exec'ing before that.

int main(void)

   char *cmd[]= {"sh", "-c", "gcc tmp.c && ./a.out", (char*)0};

    FILE *fp = fopen("tmp.c", "w");
    if (!fp) {

    fprintf(fp, "#include <stdio.h>\nint main(){puts(\"Hello World\");}");
    execv("/bin/sh", cmd);
    return (0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download