程序打印自身代码的两种方法

程序打印自身代码的两种方法


方法一:利用fopen,打开可运行程序相应的source code file


/*****************************************
code writer : EOF
code file : print_my_self.c
code date : 2014.08.01
e-mail: jasonleaster@gmail.com
code purpose :
        Aha, print out myself!

******************************************/
#include <stdio.h>
#include <fcntl.h>

#define BUFFSIZE 1024


char buffer[BUFFSIZE];

int main()
{
        FILE* fp = NULL;

        int ret = 0;

        if((fp = fopen("./print_my_self.c","r")) == NULL)
        {
                printf("Damn it,fopen failed
");
                return 0;
        }

        while((ret = fread(buffer,sizeof(char),BUFFSIZE-1,fp)) > 0)
        {
                buffer[ret-1] = '';

                printf("%s",buffer);
        }

        fclose(fp);
        return 0;
}

打印什么。。。不用说


上面这样的策略就是骗小孩儿的

另外一种方法还有点看头,只是也挺。。。没劲的。。。假设看透了的话



方法二:


           利用objcopy,然后将source code file 生成一个能够和elf格式文件合并的文件,代码中引用该文件的一个指针,最后用gcc 将两个文件共同编译进可运行程序


/*******************************************
code writer : EOF
code date : 2014.08.01
code file : test.c
code purpose:
        just a demo for a useful tool -- objcopy
and a point which was produced by the tool and 
point to the start of this file.

*******************************************/
#include <stdio.h>

extern char* _binary_test_c_start;

int main()
{
        printf("%s",(char*)&_binary_test_c_start);

        return 0;
}

jasonleaster@ubuntu:~$ objcopy -I binary -O elf64-x86-64 -B i386 test.c test.bin
jasonleaster@ubuntu:~$ gcc ./test.bin ./test.c -o ./a.out
jasonleaster@ubuntu:~$ ./a.out
/*******************************************
code writer : EOF
code date : 2014.08.01
code file : test.c
code purpose:
    just a demo for a useful tool -- objcopy
and a point which was produced by the tool and
point to the start of this file.

*******************************************/
#include <stdio.h>

extern char* _binary_test_c_start;

int main()
{

    printf("%s",(char*)&_binary_test_c_start);

    return 0;
}


思(che)考(dan):


          事实上这个demo有个“bug”,要求是代码打印自身,事实上仅仅要在main里面随便加个printf,就会打印额外的信息,打印的就不止是source code file的字符了


         另外一种方法个人看来就是提升逼格用的,感觉和第一种傻瓜使用方法没什么本质差别,都离不开原本的source code file--test.c

















原文地址:https://www.cnblogs.com/blfshiye/p/4288109.html