Linuxファイルプログラミングの一般的な関数の詳細-read()とwrite()関数


read()関数:

#include 
int read(int filedes, void *buff, int nbytes) ;//(     ,            ,          )
  :        ,       0,    - 1。            '\0', fread()  。

write()関数:

#include 
int write(int filedes, const void * buff, int nbytes) ;//(     ,         ,          )
  :          ,    - 1

#インスタンスコード:既存のファイルを新しいファイルにコピーする
#include
#include
#include
#include
#include
#include
#include 

int main(){
     
	int fd, fd1, count, ret;
	char buf[512];
	memset(buf, 0, sizeof(buf));//    0

	//        
	fd = open("example.text", O_RDONLY);
	if(fd == -1){
     
		perror("open file fail:
"
); exit(1); } printf("fd = %d
"
, fd); // fd1 = open("new_file.text", O_WRONLY | O_CREAT, 0777); if(fd1 == -1){ perror("open file fail:
"
); exit(1); } printf("fd1 = %d
"
, fd1); // buf count = read(fd, buf, sizeof(buf));// >0 ,=0 ,-1 if(count == -1){ perror("read fail:
"
); exit(1); } // while(count){ ret = write(fd1, buf, count); // >0 , -1 if(ret == -1){ perror("write"); exit(1); } printf("write bytes:%d
"
, ret); count = read(fd, buf, sizeof(buf)); } // close(fd); close(fd1); }