linux系统io的copy

时间:2023-03-09 06:52:45
linux系统io的copy

#include<stdio.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

int main(int argc,char *agrv[])

{

if(argc<3)

{

printf("Please use:mycp file1 file2\n");

return -1;

}

int file1_fd=open(agrv[1],O_RDONLY);

if(file1_fd<0)

{

return -1;

}

int len=lseek(file1_fd,0,SEEK_END);//移动到文件尾部

lseek(file1_fd,0,SEEK_SET);//文件指针恢复文件头

int file2_fd=open(agrv[2],O_WRONLY|O_CREAT,00777);//00777打开的权限

if(file2_fd<0)

{

close(file1_fd);

return -1;

}

char buf[len];

int ret=read(file1_fd,buf,len);

ret=write(file2_fd,buf,ret);

close(file1_fd);

close(file2_fd);

return 0;

}

1.打开文件

int open(const char *pathname, int flags);

参数:

const char *pathname--要打开的文件路径

int flags---打开文件的方式(权限)

O_RDWR---打开文件可读可写

O_RDONLY--只读

O_WRONLY--只写

O_CREAT--创建

O_APPEND---追加

返回值:文件描述符:(非负整数)

int fd:打开成功返回非负整数, 打开失败返回-1

程序一运行系统就会打开3个文件(0,1,2)输入,输出,出错

2.文件偏移:lseek

#include <sys/types.h>

#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);

参数:

int fd:文件描述符

off_t offset:相对whence的偏移量(正往后偏移,负数往前偏移)

int whence:参照位置文 件当前位置SEEK_CUR,文件头SEEK_SET,文件尾SEEK_END

off_t len:偏移量

例子:

off_t len = lseek(fd, 0, SEEK_END); ---会得到文件大小len

lseek(fd, 0, SEEK_SET);--把文件指针恢复到文件开头

3.往文件中写数据:write

ssize_t write(int fd, const void *buf, size_t count)

参数:

int fd:打开文件的描述符

const void *buf:写入文件中的数据

size_t count:最长可以写多少个字节

ssize_t :实际写到文件中字节数

例子:

char buf[] = "爱我中华";

int len = write(fd, buf, sizeof(buf));

系统文件例子:

4.读数据:read

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);

参数:

int fd:打开文件的描述符

void *buf:用来保存从文件中读出来的数据

size_t count:最长可以读多少个字节

ssize_t :实际读到数据字节数

例子:

char buf[128];

int len = read(fd, buf, sizeof(buf));

5.主函数:main传递参数

int main(int argc, char **argv)//或argv[]

参数:main -l -a

int argc:程序运行时候传入的参数个数 3

char **argv:程序运行时候传入的参数列表 (main, -l, -a)

例子:

int main(int argc, char **argv)

{

printf("argc = %d\n", argc);

printf("%s %s %s\n",argv[0], argv[1], argv[2]);

int fd1 = open(argv[1], O_RDONLY);

int fd2 = open(argv[2], O_WRONLY|O_CREAT, 00777);

}

程序运行 ./main file1 file2