嵌入式Linux C编程学习之路(八)——read/write,lseek函数,cp指令的代码实现

#近期学习笔记一次性加入博客

1. write

 write(intfd, void *buf, size_t count ):

第一个参数:向哪一个文件中去写;第二个参数:向这个文件中写什么内容;第三个参数:向这个文件中写多少个。

返回值:是实际写的字节数。

 

2. read

read(intfd, void *buf, size_t count)

第一个参数:从哪一个文件中去读;第二个参数:读到什么地方去;第三个参数:读多少个。

返回值:是实际读的字节数

 

3. lseek

每个内核文件都有个文件读写位置指针,可以通过lseek函数调整这个位置。

leek(intfd, off_t offset, int whence),该函数的头文件:sys/types.h  unistd.h;

功能:调整读写的位置指针;

第一个参数:要调整的文件的文件描述符;

第二个参数:偏移量,每一读写操作所需要移动的距离,单位是字节的数量,可正可负(向前移,向后移);

第三个参数:当前位置的基点,有三个标志,

SEEK_SET:当前位置为文件的开头,新位置为偏移量的大小;

SEEK_CUR:当前位置为文件指针的位置,新位置为当前位置加上偏移量。

SEEK_END:当前位置为文件的结尾,新位置为文件的大小加上偏移量的大小。

函数的返回值:成功:文件当前的位置,出错:-1。

 

4. 示例,简单实现cp命令,拷贝文件

#include "stdio.h"

#include "unistd.h"

#include "fcntl.h"

#include "string.h"

int main(int argc,char *argv[]){

int rd_fd,wr_fd;

char read_buf[128] = {0};

int rd_ret = 0;

if(argc < 3){

printf("Please input src file and dst file \n");

return -1;

}

rd_fd = open(argv[1],O_RDONLY);

if(rd_fd < 0){

printf("open src file %s error\n",argv[1]);

return -2;

}

printf("open src file %s success, rd_fd = %d\n",argv[1],rd_fd);

 

wr_fd = open(argv[2],O_WRONLY);

if(wr_fd < 0){

printf("open dst file %s error\n",argv[2]);

return -3;

}

printf("open dst file %s success, wr_fd = %d\n",argv[2],wr_fd);

 

while(1){

rd_ret = read(rd_fd,read_buf,128);

if(rd_ret < 128){

break;

}

write(wr_fd,read_buf,rd_ret);

memset(read_buf,0,128);

}

write(wr_fd,read_buf,rd_ret);

close(rd_fd);

close(wr_fd);

return 0;

}

猜你喜欢

转载自blog.csdn.net/Alone_k/article/details/81674314
今日推荐