- 论坛徽章:
- 0
|
题目:不使用文件操作,写一个把自己的源码内容打印出来的C程序。
下面是我写的程序。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char* pat = "#include <stdlib.h>#include <stdio.h>#include <string.h>int main(){char* pat = !;int len = strlen(pat);char* self;char* ps;char* pc;int num = 0;pc = pat;while (*pc){ if (*pc==123) num += 2; if (*pc==62 || *pc==125 || *pc==59) num += 1; pc++;}self = malloc(2*len+num+2);pc = pat;ps = self;while (*pc != '!'){ if (*pc==123) *ps++ = 10; *ps++ = *pc; if (*pc==62 || *pc==123 || *pc==125 || *pc==59) *ps++ = 10; pc++;}*ps++ = 34;strncpy(ps, pat, pc - pat);ps += pc - pat;*ps++ = '!';strcpy(ps, pc+1);ps += len - (pc - pat) -1;*ps++ = 34;while (*++pc){ if (*pc==123) *ps++ = 10; *ps++ = *pc; if (*pc==62 || *pc==123 || *pc==125 || *pc==59) *ps++ = 10;}*ps = 0;printf(self);free(self);return 0;}";
int len = strlen(pat);
char* self;
char* ps;
char* pc;
int num = 0;
pc = pat;
while (*pc)
{
if (*pc==123) num += 2;
if (*pc==62 || *pc==125 || *pc==59) num += 1;
pc++;
}
self = malloc(2*len+num+2);
pc = pat;
ps = self;
while (*pc != '!')
{
if (*pc==123) *ps++ = 10;
*ps++ = *pc;
if (*pc==62 || *pc==123 || *pc==125 || *pc==59) *ps++ = 10;
pc++;
}
*ps++ = 34;
strncpy(ps, pat, pc - pat);
ps += pc - pat;
*ps++ = '!';
strcpy(ps, pc+1);
ps += len - (pc - pat) -1;
*ps++ = 34;
while (*++pc)
{
if (*pc==123) *ps++ = 10;
*ps++ = *pc;
if (*pc==62 || *pc==123 || *pc==125 || *pc==59) *ps++ = 10;
}
*ps = 0;
printf(self);
free(self);
return 0;
}
从“char* pat = ”那一行至连续的下数5行代码,源文件中是在一行上,这里自动折行了。
运行的结果self.exe >> out.txt,self.c 和 out.txt两个文件在字节水平上一模一样,完全相同。
注意:self.c中不能增删空行、空格和TAB,否则打印的内容会不完全一致,除非你看懂了程序,知道怎么修改pat字符串。
我是在VC6上编写和测试的。
|
|