while循环中调用write()函数,为什么只执行一次?解决方案
发布时间:2011-06-27 17:39:57 文章来源:www.iduyao.cn 采编人员:星星草
while循环中调用write()函数,为什么只执行一次?
函数如下所示,在while循环中,从发fd1 read()一个字节数据(如“a”),通过lseek设置fd2的偏移量,然后write() fd2 ;在本程序中共执行10次循环,fd2 应该被写入了十次数据,且每次写入的数据位置不同,也就是fd2中应该有10个“a”,但是fd2中只有1个
我感觉好像是lseek()或write()在10次循环中只运行了一次,为什么?
如果不使用循环,lseek()或write()顺序写,这样fd2中的数据就正常了
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,char* argv[]){
int fd1,fd2;
char buffer[100];
long offset=0;
int num,i;
if(argc!=3){
printf("Usage : %s source dest",argv[0]);
return 1;
}
if((fd1=open(argv[1],O_RDONLY))==-1){
perror("Cannot open the file");
return 1;
}
if((fd2=open(argv[2],O_CREAT | O_WRONLY,0777))==-1){
perror("Cannot create the destination file");
return 1;
}
i=10;
while(i--){
printf("offset=%dn",offset);
num=read(fd1,buffer,10);
if(lseek(fd2,offset,SEEK_SET)==-1){
perror("Cannot move the file pointer");
return 1;
}
if(write(fd2,buffer,num)==-1){
perror("Cannot write the file content to the file");
return 1;
}
offset=offset+20;
if(lseek(fd2,offset,SEEK_SET)==-1){
perror("Cannot move the file pointer");
return 1;
}
if(write(fd2,buffer,num)==-1){
perror("Cannot write the file content to the file");
return 1;
}
}
close(fd1);
close(fd2);
return 0;
}
------解决方案--------------------
num=read(fd1,buffer,10);
你把read放在循环里了,fd1对应的文件内容太短了吧
循环一次就全读完了,然后下次循环读不到数据,自然什么也没写进去,每次write的num都是0
如果文件大些就正常了吧
又或者我猜你的意思应该是把这行read放在while上面?
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。
其他相似内容:
-
在ubuntu下怎么播放swf 和csf 文件?
虽然,firefox 可以播放swf文件,但是没有托动条。
在ubuntu下怎么播放swf和 csf文件?
哪个高...
-
2011年最新录制的Linux(CentOS)视频教程
电驴地址:http://www.verycd.com/topics/2875873/
------解决方案--------------------
l...
-
求《操作系统:设计与实现》pdf
A.S.Tanenbaum写的《操作系统设计与实现》,有上下册,谁有的,帮个忙,非常感谢。qifeifei@live.cn
----...
-
linux用户态内存的物理地址问题?
小弟我看linux内存管理一段时间了。有一个问题一直不解。 linux用户态进程使用0—3G的线性地址...
-
安装linux chm阅读器 xchm
[root@localhost ~]# yum install chmlib
[root@localhost ~]# yum install wxGTK
[root@localhost ~]...
-
都说Linux是开源的,在哪可以找到Linux的源码?
都说Linux是开源的,在哪可以找到Linux的源码?
烦请各位高手指点一二,谢谢。
------解决...
-
求解2个概念,书上没找到,急用,谢谢大家
1.Unix中磁盘文件和设备文件的异同点。
2.Unix中原子和竞争的概念。
求正解,因为考试可能会考...
-
有人在fedora 10下安装 oracle database 11g,没有呀?提供个安装步骤
有人在fedora 10下安装 oracle database 11g,没有呀?提供个安装...
-
用什么学习函数库?
我们现在学习LINUX 编程,读程序时候有很多头文件,代码中有许多库函数。
#include <sys/types.h>
#include <wait....
-
linux下c语言写的shell,花了不少时间写得 有兴趣的可以看看,本人linux初学者
http://download.csdn.net/source/2799757
------解...