【发布时间】:2021-08-24 15:31:14
【问题描述】:
-
您好,我正在尝试制作一个可以打印自己源代码的 C 程序。
-
我假设源代码文件和执行文件在同一个目录下,没有任何其他.c文件。
-
好吧,我尝试了很多代码,但都没有成功。
-
错误原因是因为命令的顺序(如果是windows命令先传入windows操作系统,如果是linux命令先传入linux操作系统)。
-
我试图忽略 fopen 和其他功能,只使用简单的操作系统命令。
-
这是我尝试过的代码:
在 Windows 上工作的代码:
/* C library statement */
#include <stdlib.h>
/* main program */
int main()
{/* start of main */
int windows = 0; /* a variable to check if we are running windows or unix operation system */
/* system function returns -1 value if it failed.
* so if unix value is -1 we are not running unix system.
* if we are not running unix system we will execute windows commands.
*/
windows = system("type *.c"); /* windows command to print file text */
if(windows == -1) /* if windows command failed (and the specific file is exists) then we are not running windows operation system */
system("cat *.c"); /* unix command to print file text */
return 0;
}/* end of main */
在 linux 上工作的代码:
/* this program will print herself source code by using simple linux or windows commands */
#include <stdlib.h>
/* main program */
int main()
{/* start of main */
int unix = 0; /* a variable to check if we are running windows or unix operation system */
/* system function returns -1 value if it failed.
* so if unix value is -1 we are not running unix system.
* if we are not running unix system we will execute windows commands.
*/
unix = system("cat *.c"); /* unix command to print file text */
if(unix == -1) /* if unix command failed (and the specific file is exists) then we are not running unix operation system */
system("type *.c"); /* windows command to print file text */
return 0;
}/* end of main */
问题是 linux 将 type 识别为 bash 命令,而 windows 没有编译 cat 命令
【问题讨论】:
-
使用标准文件 IO 函数使程序可移植(
fopen、fread和朋友) -
#1 中描述的程序类型的术语是“quine”。
-
您应该发布有效的代码作为答案,而不是编辑到问题帖子中。
-
@Armali 抱歉,我会解决这个问题,我是这个论坛的新手。