2015年8月30日 星期日

[C筆記]系統呼叫system()

前言: C語言幾乎仰賴著作業系統,system call 存在於核心,是C與OS溝通             的橋梁。


system()使用範例遇到的問題:

我嘗試了無數次cmd指令  echo %s %s >> reports.log
最後發現在我的%s裡面存在著\n換行字元導致我一直只有echo出前面的%s
剛好fgets這方法尾巴會加上換行字元 以及now()的回傳字串也有

sample code:


#include <stdlib.h>
#include <string.h>
#include <time.h>

char* now()
{
      time_t t;
      time(&t);
      return asctime(localtime(&t));//結尾會自動加上\n導致echo指令出錯
      }
      
      int main()
      {
          
          char comment[80];
          char cmd[120]; 
          fgets(comment,80,stdin); //fgets結尾會自動加上\n導致echo指令出錯
          if(comment[strlen(comment)-1] =='\n')
             comment[strlen(comment)-1] ='\0';//將\n用字串結尾取代
 
            char x[strlen(now())];
            int i;
            for(i=0;i<strlen(now());i++)
            {
              x[i]= *(now()+i); //*now存在記憶體的實字字串(不能修改)所以先丟到陣列進行修改
                                        }
          if(x[strlen(x)-4]=='\n')
             x[strlen(x)-4]='\0';
   
          sprintf(cmd,"echo %s %s >> reports.log",x,comment);
          system(cmd);
          return 0;
          }

輸出結果



          

沒有留言:

張貼留言