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

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


方法一:利用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\n");
                return 0;
        }

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

                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

















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值