#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#define N 1024
int main(int argc,char *argv[])
{
char buf[N];
char *ptr;
int fd1;
int fd2;
int readsize;
int writesize;
if(fd1=open("/root/program/sfile/openfile.c",O_RDONLY)<0)
{
printf("openfile 1 failed\n");
exit(1);
}
printf("openfile 1 successed\n");
readsize=read(fd1,buf,N);
printf("%dB data is readed\n",readsize);
if(fd2=open("/root/program/sfile/des.c",O_CREAT|O_WRONLY,0755)<0)
{
printf("openfile 2 failed\n");
exit(1);
}
printf("openfile 2 successed\n");
ptr=buf;
writesize=write(fd2,ptr,readsize);
printf("%dB data is writed\n",writesize);
close(fd1);
close(fd2);运动会加油稿
}
运行结果:
[root@cfc sfile]# ./copy
openfile 1 successed
然后就一直停在那里
当按下回车键时:
出现:
1B data is readed
openfile 2 successed
1B data is writed
[root@cfc sfile]#
if(fd1=open("/root/program/sfile/openfile.c",O_RDONLY)<0)
if(fd1=open("/root/program/sfile/openfile.c",O_RDONLY)<0),这一句运算符优先级的问题,先比较open("/root/program/sfile/openfile.c",O_RDONLY)<0,再把结果给fd1,这里正常打开文件、fd1为0,变成了从标准输入读取数据,所以在read函数那里等待你输入并回车才执行完read函数,加个括号就是了:
if ((fd1 = open("/root/program/sfile/openfile.c", O_RDONLY)) < 0)