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.youkuaiyun.com/detail/erujo/8937043