线程中复制大文件问题
本帖最后由 chenjie901 于 2012-10-23 23:22 编辑以下程序意思是启一个线程复制b.txt的内容到a.txt中,b.txt有3144行。 a.txt每行内容为1234567890十个数,一共3144行。
我的问题是,为什么只复制了2859行,但程序输出说些了31440个字符?
代码如下:#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int exit_code = 0;
#define BUFF_TO_READ 31440
#define BUFF_TO_WRITE 31440
void *copy_file(void *content)
{
//pthread_detach(pthread_self());
printf("child thread id is %x\n", pthread_self());
//sleep(5);
printf("%s:%x\n", content, pthread_self());
int source = open("b.txt", O_RDONLY);
if (-1 == source) {
perror("open b.txt failed");
}
int des = open("a.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR);
if (-1 == des) {
perror("open a.txt failed");
}
char buf;
int nleft = BUFF_TO_READ;
int nread = 0;
char *ptr = buf;
while (nleft > 0) {
nread = read(source, ptr, nleft);
if (-1 == nread) {
perror("read source error");
break;
}
printf("read %d bytes\n", nread);
nleft -= nread;
ptr += nread;
}
nleft = BUFF_TO_WRITE;
int nwrite = 0;
ptr = buf;
while(nleft > 0) {
nwrite = write(des, ptr, nleft);
if ( -1 == nwrite) {
perror("write source error");
break;
}
printf("write %d bytes\n", nwrite);
nleft -= nwrite;
ptr += nwrite;
}
fsync(des);
return ((void *)&exit_code);
//pthread_exit(&exit_code);
}
int *ret = 0;
int main()
{
pthread_t tid;
char buf[] = "hello,I'm thread";
if (-1 == pthread_create(&tid, NULL, copy_file, buf)) {
perror("tread_create failed");
}
printf("parent thread id is %x\n", pthread_self());
pthread_join(tid, NULL);
printf("all exit\n");
return 0;
}运行结果如下:
========================
# ./a.out
parent thread id is b7f576c0
child thread id is b7f56b90
hello,I'm thread:b7f56b90
read 31440 bytes
write 31440 bytes
all exit
========================
求解释??? 没人理我啊,好吧,我找到原因了没考虑换行符
页:
[1]