不得不谈一下 writeread 及其参数

# read()

int read(int fd,char* buf,int count);

从文件中向缓冲区中读取字节

返回值

大于0 :成功读取的字节数

等于0 :到达文件末尾

-1 :发生错误,通过 errno 确定具体错误解释

# write()

# 函数原型

#include "unistd.h"
ssize_t write(int fd,const void *buf,size_t count);

# 功能

从缓冲区向 fd 所指向的文件写入数据

write 返回值

调用成功 返回所写的字符个数

调用失败 返回 -1 ,并给 errno 自动设置错误号,使用 perror 这样的函数,就可以自动将 errno 中的错误号转化为错误解释

# 参数

fd 指向打开的文件

buf 保存数据的缓存空间的起始地址

count 从起始地址算起,把缓存中 count 个字符,写入 fd 指向的文件

连起来就是从 buf 起始地址算起,将 count 个字符写入 fd 所指向的文件中

#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "fcntl.h"
int main(int argc, char *argv[])
{
	int infd,outfd; 
	char buff[1024];
	char *fileName[2];
	int fileArg=0;
	int i;
	int read_num,write_num;
	for(i=0;i<argc;i++){
		if(argv[i][0]=='-')
			printf("This is an option!\n");
		else
			fileName[fileArg++]=argv[i];
	}
//make infd
	infd=open(fileName[0],O_RDONLY);
	if(infd==-1){
		printf("Fail to open the file %s\n",fileName[0]);
		return 1;
	}
//make outfd
 	outfd=open(fileName[1],O_WRONLY|O_CREAT,0600);
 	if(outfd==-1){
 		printf("Fail to open the file %s\n",fileName[1]);
 		return 1;
 	}
 //kcopy
  	while((read_num=read(infd,buff,sizeof(buff)))>0){
  		write_num=write(outfd,buff,read_num);
  		if(read_num!=write_num)
  			printf("Not match!\n");
  	}
  	close(infd);
  	close(outfd);
	return 0;
}
更新於 閱讀次數

請我喝[茶]~( ̄▽ ̄)~*

fygod 微信支付

微信支付

fygod 支付寶

支付寶

fygod PayPal

PayPal