1. 程式人生 > >linux c 檔案重定向 ,很好的程式碼。

linux c 檔案重定向 ,很好的程式碼。

#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
   #define STDOUT 1   //標準輸出檔案描述符 號

   int nul, oldstdout;
   char msg[] = "This is a test";

   /* create a file */

//開啟一個檔案,操作者具有讀寫許可權 如果檔案不存在就建立
   nul = open("DUMMY.FIL", O_CREAT | O_RDWR,
      S_IREAD | S_IWRITE);

   /* create a duplicate handle for standard
      output */

//建立STDOUT的描述符備份
   oldstdout = dup(STDOUT);
   /*
      redirect standard output to DUMMY.FIL
      by duplicating the file handle onto the
      file handle for standard output.
   */

//重定向nul到STDOUT
   dup2(nul, STDOUT);

   /* close the handle for DUMMY.FIL */

//重定向之後要關閉nul
   close(nul);

   /* will be redirected into DUMMY.FIL */

//寫入資料
   write(STDOUT, msg, strlen(msg));

   /* restore original standard output
      handle */

//還原
   dup2(oldstdout, STDOUT);

   /* close duplicate handle for STDOUT */
   close(oldstdout);

   return 0;
}