linux系统应用编程学习–文件IO
1,学习框架
2,练习:编写一个cp命令实现文件复制:1-my_cp.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_SIZE 128
int main(int argc,char *argv[])
{
int fd1,fd2;
int buf[MAX_SIZE],size;
if(argc !=3){
printf("cmd error!\n");
return -1;
}
if( (fd1=open(argv[1],O_RDONLY)) ==-1){
printf("open source file error!\n");
return -1;
}
if( (fd2=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0777)) ==-1){
printf("open/create dist file error!\n");
return -1;
}
while( (size =read(fd1,buf,MAX_SIZE)) >0){
if( write(fd2,buf,size) == -1){
printf("wirte error!\n");
}
}
close(fd1);
close(fd2);
printf("cp execute finish\n");
}
测试:复制一份.c文件;./my_cp ./1-my_cp.c ./file_cp
执行后file_cp和1-my_cp.c大小相等,
用cat ./file_cp查看内容与源文件完全相同;
gavin@vm-ubuntu:~/2exercise/0-fileIO$ ls
1-my_cp.c my_cp
gavin@vm-ubuntu:~/2exercise/0-fileIO$ ./my_cp ./1-my_cp.c ./file_cp
cp execute finish
gavin@vm-ubuntu:~/2exercise/0-fileIO$ ll
total 28
drwxrwxr-x 2 gavin gavin 4096 8月 11 15:29 ./
drwxrwxr-x 5 gavin gavin 4096 8月 11 14:29 ../
-rw-rw-r-- 1 gavin gavin 789 8月 11 15:10 1-my_cp.c
-rwxrwxr-x 1 gavin gavin 789 8月 11 15:29 file_cp*
-rwxrwxr-x 1 gavin gavin 8864 8月 11 15:28 my_cp*
gavin@vm-ubuntu:~/2exercise/0-fileIO$
3,总结:
a,利用man 2 function_name 查看函数的用法和关联的头文件;
b,在打开目标文件时,如果不指定文件权限,复制完成后,打开它时会提示权限不够。
4, 文件定位 lseek
根据man 2 lseek 可知,返回值是相对文件开始的byte偏移数;
RETURN VALUE
Upon successful completion, lseek() returns the resulting offset loca‐
tion as measured in bytes from the beginning of the file
可以编写一个获取文件字节数的程序:2-lseek.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc ,char *argv[])
{
int fd;
int size;
if(argc !=2){
printf("cmd error!\n");
return -1;
}
if( (fd =open(argv[1],O_RDONLY)) ==-1){
printf("open file fail!\n");
return -1;
}
size =lseek(fd,0,SEEK_END);
printf("The length of %s is %d byte \n",argv[1],size);
close(fd);
return 1;
}
测试得到文件的字节数496,与用ll查看到的2-lseek.c大小一致。
gavin@vm-ubuntu:~/2exercise/0-fileIO$ ./lseek ./2-lseek.c
The length of ./2-lseek.c is 496 byte
gavin@vm-ubuntu:~/2exercise/0-fileIO$
gavin@vm-ubuntu:~/2exercise/0-fileIO$ ll
-rw-rw-r-- 1 gavin gavin 496 8月 11 16:20 2-lseek.c
-rwxrwxr-x 1 gavin gavin 8808 8月 11 16:20 lseek*