69,381
社区成员
发帖
与我相关
我的任务
分享
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv)
{
int fd, fd_b;
int ret = 0;
char buffer[128];
if((fd = open("snake.c", O_RDONLY),0666) < 0)
{
printf("First file open fail!\n");
exit(-1);
}
if((fd_b = open("test_new.c", O_CREAT | O_WRONLY | O_TRUNC), 0666) < 0)
{
printf("Second file open fail!\n");
exit(-1);
}
//运行完后为什么test_new.c文件总是比原文件多几行呢??非常不理解!
while(1)
{
if((ret = read(fd, buffer, sizeof(buffer) - 1)) < 0)
{
printf("read fail!\n");
exit(-1);
}
if(write(fd_b, buffer, strlen(buffer) - 1) < 0)
{
printf("write fail!\n");
exit(-1);
}
//这个地方是如果读取完了,返回读的数小于buffer那么就应该退出。
if(ret < (sizeof(buffer))-1)
{
break;
}
}
printf("buffer = %s\n", buffer);
close(fd);
close(fd_b);
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv)
{
int fd, fd_b;
int ret = 0;
char buffer[128];
if((fd = open("snake.c", O_RDONLY)) < 0)
{
printf("First file open fail!\n");
exit(-1);
}
if((fd_b = open("test_new.c", O_CREAT | O_WRONLY | O_TRUNC, 0666)) < 0)
{
printf("Second file open fail!\n");
exit(-1);
}
while(1)
{
if((ret = read(fd, buffer, sizeof(buffer) - 1)) < 0)
{
printf("read fail!\n");
exit(-1);
}
//这样就不会多出来那些不想要的行数了
buffer[ret] = '\0';
if(write(fd_b, buffer, strlen(buffer) - 1) < 0)
{
printf("write fail!\n");
exit(-1);
}
//这个地方是如果读取完了,返回读的数小于buffer那么就退出。
if(ret < (sizeof(buffer))-1)
{
break;
}
}
close(fd);
close(fd_b);
return 0;
}