跳轉到內容

C 語言入門/C 標準實用程式庫和時間庫

來自華夏公益教科書,自由的教科書

實用程式庫包含許多函式。它需要以下宣告

   #include <stdlib.h>

有用的函式包括

   atof( <string> )     Convert numeric string to double value.
   atoi( <string> )     Convert numeric string to int value.
   atol( <string> )     Convert numeric string to long value.
   rand()               Generates pseudorandom integer.
   srand( <seed> )      Seed random-number generator -- "seed" is an "int".
   exit( <status> )     Exits program -- "status" is an "int".
   system( <string> )   Tells system to execute program given by "string".
   abs( n )             Absolute value of "int" argument.
   labs( n )            Absolute value of long-int argument.

如果函式 "atof()", "atoi()", 和 "atol()" 無法將給定的字串轉換為數值,它們將返回 0。

時間和日期庫包含各種各樣的函式,其中一些函式比較晦澀且非標準。此庫需要以下宣告

   #include <time.h>

最基本的函式是 "time()",它返回自 1970 年 1 月 1 日協調世界時 (UTC) 子夜起經過的秒數(不包括閏秒)。它返回一個 "time_t" 型別的數值(一個 "long" 型別),如標頭檔案中定義。

以下函式使用 "time()" 來實現一個以秒為單位的解析度的程式延遲

   /* delay.c */

   #include <stdio.h>

   #include <time.h>

   void sleep( time_t delay );

   void main()
   {
     puts( "Delaying for 3 seconds." );
     sleep( 3 );
     puts( "Done!" );
   }

   void sleep( time_t delay )
   {
     time_t t0, t1;
     time( &t0 );
     do
     {
       time( &t1 );
     }
     while (( t1 - t0 ) < delay );
   }

"ctime()" 函式將 "time()" 返回的時間值轉換為一個時間和日期字串。以下小程式列印當前時間和日期

   /* time.c */

   #include <stdio.h>
   #include <time.h>

   void main()
   {
     time_t *t;
     time( t );
     puts( ctime( t ) );
   }

此程式列印一個如下形式的字串

   Tue Dec 27 15:18:16 1994

進一步閱讀

[編輯 | 編輯原始碼]
華夏公益教科書