1. 基于C语言实现,文件IO练习
2. 代码实现
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
typedef struct
{
const char *src;
const char *dest;
int start;
int len;
} info_t;
int get_src_file_len(const char *srcfile, const char *destfile)
{
int sfd, dfd;
int len = 0;
if ((sfd = open(srcfile, O_RDONLY)) == -1)
{
printf("open srcfile error");
}
if ((dfd = open(destfile, O_RDWR | O_CREAT | O_TRUNC, 0664)) == -1)
{
printf("open destfile error");
}
len = lseek(sfd, 0, SEEK_END);
close(sfd);
close(dfd);
return len;
}
int copy_file(const char *srcfile, const char *destfile, int start, int len)
{
int sfd, dfd;
char buf[10] = {0};
int ret = 0;
int i = 0;
if ((sfd = open(srcfile, O_RDONLY)) == -1)
{
printf("open srcfile error");
}
if ((dfd = open(destfile, O_RDWR)) == -1)
{
printf("open destfile error");
}
lseek(sfd, start, SEEK_SET);
lseek(dfd, start, SEEK_SET);
while (1)
{
ret = read(sfd, buf, sizeof(buf));
i += ret;
if (ret == 0 || i > len)
{
write(dfd, buf, ret - (i - len));
break;
}
write(dfd, buf, ret);
}
close(sfd);
close(dfd);
return 0;
}
void *task(void *arg)
{
info_t f = *(info_t *)arg;
copy_file(f.src, f.dest, f.start, f.len);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
if (argc != 3)
{
fprintf(stderr, "input error,try again\n");
fprintf(stderr, "usage:./a.out srcfile,destfile\n");
exit(EXIT_FAILURE);
}
int len= get_src_file_len(argv[1], argv[2]);
info_t f[] = {
{argv[1], argv[2], 0, len / 2},
{argv[1], argv[2], len / 2, (len - len / 2)},
};
pthread_t tid1, tid2;
if (pthread_create(&tid1, NULL, task, (void *)&f[0]))
printf("thread 1 create error");
if (pthread_create(&tid2, NULL, task, (void *)&f[1]))
printf("thread 2 create error");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
执行结果

6. 非原创