write()函數簡介

   write函數(寫入文件)
它的主要功能是:將某個文件緩衝區的數據,寫入某個文件內。
系統調用格式:
number = write(handle, buffer, n) ;
write函數各個參數定義如下:
l         handle:  這是一個已經打開的文件句柄,表示將數據寫入這個文件句柄所表示的文件內。
l         buffer:  表示緩衝區,也就是把這個緩衝區的數據寫入文件句柄所表示的文件內。
l         n:         表示調用一次write操作,應該寫如多少字符。
l         number:表示系統實際寫入的字符數量。
如果調用write失敗,則系統返回-1給number。

Code:
#include "lyl.h"
#define BUF 512
#define PERM 0744
/*本程序會將某個文件內容複製到所指定的文件中。*/
main( int argc,char *argv[])
{
    char buffer[BUF] ;
    int source,dest ;
    int count ;

    if ( argc != 3 )
    {
        printf("sorry input error!\n") ;
        exit(1) ;
    }

    source = open(argv[1],O_RDONLY) ;       /*open source file*/
    if ( source == -1 )
    {
        printf("sorry input error!\n") ;
        exit(1) ;
}

    dest = creat(argv[2],PERM);         /*create dest file*/
    if ( dest == -1 )
    {
        printf("create [%s] file error\n",argv[2]);
        exit(1);
    }

    while( (count = read(source,buffer,BUF)) > 0 )
        write(dest,buffer,count);

    exit(0) ;
}
$more t1.txt
1234567890
$ more t2.txt

$cc -o write write.c ;write t1.txt t2.txt
$more t2.txt
1234567890

本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u/22541/showart_173937.html
發佈了4 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章