现在的位置: 首页 > 综合 > 正文

延时程序执行不推荐system(“pause”)方法

2013年08月10日 ⁄ 综合 ⁄ 共 1063字 ⁄ 字号 评论关闭

    最近我看到有些人在想要让他们的程序延时的时候使用了system(“pause”)。我不知道是谁教给他们的这种方法,但这肯定不是一个好的习惯。通过调用system()函数,程序会调用默认的shell(命令行解释器)程序,然后shell程序会执行给定的命令行参数(在这个例子中是“pause”)。也就是说它会执行“pause.exe”程序。现在简单的c程序要依赖两个外部的程序来完成一个类似“按任意键继续”这样一个功能。想象一下,假如现在有人删除或重命名了“pause.exe”又会怎么样呢?假如有人想要在UNIX或者Mac上编译你的程序又会怎么样呢?你的程序会出错,你会得到一个令人讨厌的shell信息而不是pause这个功能。为什么本来能够用c语言本身实现的功能非得要调用两个外部程序呢

 对于要开始实现这个功能的人,这里有一个用c语言实现同样功能的代码

Code:

#ifndef WIN32
 #include <unistd.h>
#endif

#ifdef __cplusplus
 #include <iostream>
  #ifndef WIN32
   #include <stdio.h>
  #endif
 using namespace std;
#else
 #include <stdio.h>
#endif

#define WAIT_MSG "press enter to continue..."

/*
 note that the function "pause" already exists in <unistd.h>
 so i chose user_wait() for it.
*/
void user_wait()
{
  int c;

#ifdef __cplusplus
  cout << WAIT_MSG << endl;
#else
  printf("%s/n", WAIT_MSG);
#endif
  /* eat up characters until a newline or eof */
  do
  {
    c = getchar();
    if(c == EOF) break;
  } while(c != '/n');
}

 

int main(int argc, char *argv[])
{
  printf("hello/n");
  user_wait();
  printf("goodbye/n");
  return 0;
}

   使用这个代码的主要问题是控制台io通常是line buffered的终端,所以要用回车键代替任意键。有一些根据具体系统的方法来替代这个方法(“pause.exe”就是这样做的),但是这段代码对于大多数系统来说是可移植的。

 

抱歉!评论已关闭.