lseek文件偏移量
/*拷贝多份文件*/
#include
#include // open
#include
#include // exit
#include // read
#define NUM 3
#define LEN 10
int main(void) {
int fdRead = -1;
int fdWrite = -1;
char * readName = "./log.txt";
const char writeName[10] = "./copy";
off_t offset = -1;
ssize_t size = -1;
char buf[LEN] = {0};
char * ptr = NULL;
char lastName[5] = {0};
char firstName[20] = {0};
// 打开文件
fdRead = open(readName, O_RDONLY);
if (fdRead == -1) {
perror("error open:");
exit(EXIT_FAILURE);
}
// 循环拷贝
printf("copy");
for (int i = 0; i < NUM; i++) {
// 重新设定偏移量
offset = lseek(fdRead, 0, SEEK_SET);
// 自定义文件名
strcpy(firstName, writeName);
sprintf(lastName, "_%d", i);
strcat(firstName, lastName);
strcat(firstName, ".txt");
printf("create file:%s\n", firstName);
// 打开创建copy文件
fdWrite = open(firstName, O_WRONLY | O_CREAT);
do {
size = read(fdRead, buf, LEN);
ptr = buf;
if (size > 0) {
printf("read %ld bytes:\n", size);
write(fdWrite, ptr, size);
} else {
printf("reach the end of file.\n");
}
} while (size > 0);
close(fdWrite);
}
close(fdRead);
return 0;
}