Linux---open,write,read,close函數(shù)
2021-11-22 08:05 作者:風(fēng)菩提樹 | 我要投稿
1.open函數(shù)
打開一個(gè)指定的文件并獲得一個(gè)文件描述符
用法:
int?fd?=?open("threetxt",O_RDWR|O_CREAT|O_TRUNC);

2.write函數(shù)
將數(shù)據(jù)寫入指定的文件
用法:
char a[45] = "你是不是一個(gè)好人?";
int write_res = write(open_fd,a,strlen(a));
if(write_res == ERR_NUM)
{
perror("write1");
return ERR_NUM;
}

3.read函數(shù)
從指定的文件讀取數(shù)據(jù)
用法:
? ??
int n=read(open_fd1,array,sizeof(array));

4.close函數(shù)
關(guān)閉文件
用法:
close(fd);

5.練習(xí):用read以及write實(shí)現(xiàn)cp的功能
#include
#include
#include
#include
#include
#include
#include
int My_Cp(int open_fd1,int open_fd2);
int main(int argc , char *argv[])
{
if(argc != 3)
{
printf("指令有誤,請(qǐng)重新輸入!\n");
return -1;
}
if(access(argv[1],F_OK))
{
printf("沒有目標(biāo)文件:%s!",argv[1]);
return -1;
}
umask(0000);
int open_fd1 = open(argv[1],O_RDWR);
int open_fd2 = open(argv[2],O_RDWR | O_CREAT |O_TRUNC, 0777);
if(open_fd1 == -1 || open_fd2 == -1)
{
perror("open failed\n");
return -1;
}
My_Cp(open_fd1,open_fd2);
close(open_fd1);
close(open_fd2);
return 0;
}
int My_Cp(int open_fd1,int open_fd2)
{
char array[1024];
int n;
memset(array,0,1024);
while( (n=read(open_fd1,array,sizeof(array))) != 0)
{
if(n
{
perror("read");
return -1;
}
int write_res = write(open_fd2,array,n);
if(write_res == -1)
{
perror("write failed!\n");
return -1;
}
memset(array,0,1024);
}
return 0;
}
標(biāo)簽:Linux