#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
typedef struct {
off_t file_size;
ssize_t read_size;
} copy_ctx_t;
void * display_thread(void *args)
{
int done;
copy_ctx_t *ctx = (copy_ctx_t *)args;
while(ctx->read_size != ctx->file_size) {
done = (int)((double)ctx->read_size /
(double)ctx->file_size * 100);
printf("%d%% Done.", done);
fflush(stdout);
printf("\r");
usleep(1000 * 100);
}
done = (int)((double)ctx->read_size /
(double)ctx->file_size * 100);
printf("%d%% Done.", done);
fflush(stdout);
printf("\r\n");
return NULL;
}
int main(int argc, char *argv[])
{
int ret;
int src_fd;
int dst_fd;
ssize_t rn;
uint8_t buffer;
pthread_t ptid;
struct stat st;
copy_ctx_t copy_ctx;
if (argc != 3) {
printf("Usage: app src dst.\n");
return 0;
}
if (stat(argv[1], &st) == -1) {
//FIXME
}
copy_ctx.file_size = st.st_size;
copy_ctx.read_size = 0;
ret = pthread_create(&ptid, NULL,
display_thread, ©_ctx);
if (ret != 0) {
printf("create thread failed.\n");
//FIXME
}
src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
//FIXME
}
dst_fd = open(argv[2],
O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dst_fd == -1) {
//FIXME
close(src_fd);
}
for ( ; (rn = read(src_fd, &buffer, 1)) > 0 ;) {
write(dst_fd, &buffer, 1);
copy_ctx.read_size += 1;
usleep(1000 * 500);
}
pthread_join(ptid, NULL);
close(src_fd);
close(dst_fd);
return 0;
}
学习pthread的函数 读取文件 打印百分比状态
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
typedef struct {
off_t file_size;
ssize_t read_size;
} copy_ctx_t;
void * display_thread(void *args)
{
int done;
copy_ctx_t *ctx = (copy_ctx_t *)args;
while(ctx->read_size != ctx->file_size) {
done = (int)((double)ctx->read_size /
(double)ctx->file_size * 100);
printf("%d%% Done.", done);
fflush(stdout);
printf("\r");
usleep(1000 * 100);
}
done = (int)((double)ctx->read_size /
(double)ctx->file_size * 100);
printf("%d%% Done.", done);
fflush(stdout);
printf("\r\n");
return NULL;
}
int main(int argc, char *argv[])
{
int ret;
int src_fd;
int dst_fd;
ssize_t rn;
uint8_t buffer;
pthread_t ptid;
struct stat st;
copy_ctx_t copy_ctx;
if (argc != 3) {
printf("Usage: app src dst.\n");
return 0;
}
if (stat(argv[1], &st) == -1) {
//FIXME
}
copy_ctx.file_size = st.st_size;
copy_ctx.read_size = 0;
ret = pthread_create(&ptid, NULL,
display_thread, ©_ctx);
if (ret != 0) {
printf("create thread failed.\n");
//FIXME
}
src_fd = open(argv[1], O_RDONLY);
if (src_fd == -1) {
//FIXME
}
dst_fd = open(argv[2],
O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dst_fd == -1) {
//FIXME
close(src_fd);
}
for ( ; (rn = read(src_fd, &buffer, 1)) > 0 ;) {
write(dst_fd, &buffer, 1);
copy_ctx.read_size += 1;
usleep(1000 * 500);
}
pthread_join(ptid, NULL);
close(src_fd);
close(dst_fd);
return 0;
}
学习pthread的函数 读取文件 打印百分比状态