read/write 的使用
讀函數read
ssize_t read(int fd,void *buf,size_t nbyte)
read函數是負責從fd中讀取內容.成功時,read返回實際所讀的字節數,如果返回的值是0,表示已經讀到文件的結束了.
小於0表示出現了錯誤.如果錯誤爲EINTR說明讀是由中斷引起的, 如果是ECONNREST表示網絡連接出了問題.
寫函數write
ssize_t write(int fd,const void *buf,size_t nbytes)
write函數將buf中的nbytes字節內容寫入文件描述符fd.成功時返回寫的字節數.失敗時返回-1. 並設置errno變量. 在網絡程序中,當我們向套接字文件描述符寫時有倆種可能.
1)write的返回值大於0,表示寫了部分或者是全部的數據.
2)返回的值小於0,此時出現了錯誤.我們要根據錯誤類型來處理. 如果錯誤爲EINTR表示在寫的時候出現了中斷錯誤.
如果爲EPIPE表示網絡連接出現了問題(對方已經關閉了連接).
綜合實例
/*
* =====================================================================================
*
* Filename: cp_file_01.c
*
* Description: 該程序通過從待拷貝的文件中逐步讀出數據到緩衝區,再把緩衝區
* * 的數據逐個寫入到新創建的文件中,完成對原文件的拷貝工作。
*
* Version: 1.0
* Created: 07/28/2015 03:02:41 AM
* Revision: none
* Compiler: gcc
*
*
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFER_SIZE 1024
int main (int argc ,char **argv)
{
int read_fd, write_fd;
int read_bytes, write_bytes;
char buffer[BUFFER_SIZE];
char *ptr;
if(argc!=3){
fprintf(stderr,"%s from readfile \n\a",argv[0]);
exit(1);
}
/* 打開源文件 */
if((read_fd=open(argv[1],O_RDONLY))==-1)
{
fprintf(stderr,"open %s ERROR: %s \n",argv[1],strerror(errno));
exit(1);
}
/* 創建目的文件*/
if((write_fd=open(argv[2],O_WRONLY|O_CREAT,0755))==-1)
{
fprintf(stderr,"open %s ERROR: %s \n",argv[2],strerror(errno));
exit(1);
}
/*
拷貝文件,即文件的讀寫
*/
while(read_bytes=read(read_fd,buffer,BUFFER_SIZE))
{
if((read_bytes==-1)&&(errno!=EINTR))
break;
else if(read_bytes>0)
{
ptr=buffer;
while(write_bytes=write(write_fd,ptr,read_bytes))
{
if((write_bytes==-1)&&(errno!=EINTR)) //寫發生錯誤
break;
else if (write_bytes=read_bytes)
break;
//寫完了所有的字符
else if(write_bytes>0)
{//只寫了一部分字符,繼續寫
ptr+=write_bytes;
read_bytes-=write_bytes;
}
}
//寫的時候發生了錯誤
if (write_bytes==-1)
break;
}
}
close(read_fd);
close(write_fd);
}
編譯運行
[root@localhost file]# gcc -o cp_file_01 cp_file_01.c
[root@localhost file]# ./cp_file_01 read.txt write.txt
[root@localhost file]#
具體的函數說明參考linux man幫助或者 linux c 函數手冊
下載地址:
http://download.csdn.net/detail/erujo/8937043