(1)打开一个已经存在的文件(例如 src_file),使用只读方式;然后打开一个新建文件(例如 dest_file),
使用只写方式,新建文件的权限设置如下:
文件所属者拥有读、写、执行权限;
同组用户与其他用户只有读权限。
从 src_file 文件偏移头部 500 个字节位置开始读取 1Kbyte 字节数据,然后将读取出来的数据写入到
dest_file 文件中,从文件开头处开始写入,1Kbyte 字节大小,操作完成之后使用 close 显式关闭所有文件,
然后退出程序。
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int agrc, char** agrv)
{
printf("app input param num:%d", agrc);
for (size_t i = 0; i < agrc; i++)
{
printf("app input param num:%s\r\n", agrv[i]);
}
int src_fd,dst_fd = 0;
u_int8_t data[1024] = {0};
src_fd = open("./src_file", O_RDONLY);
if (-1 == src_fd)
{
printf("open src_file failed!\r\n");
}
dst_fd = open("./dst_file", O_WRONLY|O_CREAT|O_EXCL, 0x01e4);
if (-1 == dst_fd)
{
printf("open dst_file failed!\r\n");
}
int offset = lseek(src_fd, 500, SEEK_SET);
printf("cur offset:%d\r\n", offset);
int read_size = read(src_fd, data, 1024);
printf("cur read read_size:%d\r\n", read_size);
int write_size = write(dst_fd, data, 1024);
printf("cur read write_size:%d\r\n", read_size);
close(src_fd);
close(dst_fd);
return 0;
}
book@100ask:~/ward/1_chapt$ gcc -o test1 test.c //进行编译后
book@100ask:~/ward/1_chapt$ ./test1
app input param num:1
app input param num:./test1
cur offset:500
cur read read_size:1024
cur read write_size:1024
book@100ask:~/ward/1_chapt$ ls -l //查看文件,且对应文件内容也更改,权限到位
total 172
-rwxr--r-- 1 book book 1024 Jul 29 11:51 dst_file
-rw-rw-r-- 1 book book 142492 Jul 29 11:48 src_file
-rwxrwxr-x 1 book book 8344 Jul 29 11:29 test
-rw-rw-r-- 1 book book 992 Jul 29 11:47 test.c
-rwxrwxr-x 1 book book 8608 Jul 29 11:50 test1