2012-01-09 17:14:36Morris
[C/C++] 用程式碼印出自己的程式碼
方法一: 最為正統的寫法
#include<stdio.h>
#include<stdlib.h>
int main() {
char str[] = "#include<stdio.h>%c#include<stdlib.h>%cint main() {%c%cchar str[] = %c%s%c;%c%cprintf(str, 10, 10, 10, 9, 34, str, 34, 10, 10, 9, 10, 10, 9, 10);%c%cgetchar();%c%creturn 0;%c}";
printf(str, 10, 10, 10, 9, 34, str, 34, 10, 9, 10, 9, 10, 9, 10);
getchar();
return 0;
}
方法二: 利用讀檔, 但是必須宣告自己的檔名叫做 "itself.cpp"
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE *fptr;
fptr = fopen("itself.cpp", "rb");
char s[100];
while(fgets(s, 100, fptr))
printf("%s", s);
getchar();
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main() {
char str[] = "#include<stdio.h>%c#include<stdlib.h>%cint main() {%c%cchar str[] = %c%s%c;%c%cprintf(str, 10, 10, 10, 9, 34, str, 34, 10, 10, 9, 10, 10, 9, 10);%c%cgetchar();%c%creturn 0;%c}";
printf(str, 10, 10, 10, 9, 34, str, 34, 10, 9, 10, 9, 10, 9, 10);
getchar();
return 0;
}
方法二: 利用讀檔, 但是必須宣告自己的檔名叫做 "itself.cpp"
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE *fptr;
fptr = fopen("itself.cpp", "rb");
char s[100];
while(fgets(s, 100, fptr))
printf("%s", s);
getchar();
return 0;
}
下一篇:[教科書內容][整理中]
方法二不行耶...