当前位置: 技术问答>linux和unix
为什么写文件报错write(fd1,buf,count) ,errno 是9 EBADF,代码如下
来源: 互联网 发布时间:2016-01-04
本文导语: #include #include #include #include #include #include int main(int argc, char *argv[]){ int fd,fd1,count; ssize_t ss_size; char buf[1024]; char *sourcefile,*destfile; char c_writebuf[1024]; if (argc != 3) { printf("Usage: run [two parameter]"); return -1; } sou...
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[]){
int fd,fd1,count;
ssize_t ss_size;
char buf[1024];
char *sourcefile,*destfile;
char c_writebuf[1024];
if (argc != 3)
{
printf("Usage: run [two parameter]");
return -1;
}
sourcefile = argv[1];
destfile = argv[2];
printf("source file is %sn",sourcefile);
printf("dest file is %sn",destfile);
if((fd1 = open(destfile,O_CREAT,S_IRWXU)) == -1){
printf("Open Errorn Error No= %dn",errno);
return -1;
}
if ((fd = open(sourcefile,O_RDONLY)) == -1){
printf("Error can't open the source file %s",sourcefile);
return -1;
}
printf("size of buf is %dn",sizeof(buf));
while (( count = read(fd,buf,sizeof(buf)))>0)
{
if (write(fd1,buf,count) != count) //write 后出错
printf("error No=%dn",errno);
printf("write data errorn");
}
if (count == -1)
printf("read data error");
else
{
printf("Successn");
}
if (close(fd) == -1 ){
printf("Error,Can't close the sourcefile");
return -1;
}
if (close(fd1) == -1 ){
printf("Error,Can't close the destfile");
return -1;
}
printf("Successn");
return 0;
}
#include
#include
#include
#include
#include
int main(int argc, char *argv[]){
int fd,fd1,count;
ssize_t ss_size;
char buf[1024];
char *sourcefile,*destfile;
char c_writebuf[1024];
if (argc != 3)
{
printf("Usage: run [two parameter]");
return -1;
}
sourcefile = argv[1];
destfile = argv[2];
printf("source file is %sn",sourcefile);
printf("dest file is %sn",destfile);
if((fd1 = open(destfile,O_CREAT,S_IRWXU)) == -1){
printf("Open Errorn Error No= %dn",errno);
return -1;
}
if ((fd = open(sourcefile,O_RDONLY)) == -1){
printf("Error can't open the source file %s",sourcefile);
return -1;
}
printf("size of buf is %dn",sizeof(buf));
while (( count = read(fd,buf,sizeof(buf)))>0)
{
if (write(fd1,buf,count) != count) //write 后出错
printf("error No=%dn",errno);
printf("write data errorn");
}
if (count == -1)
printf("read data error");
else
{
printf("Successn");
}
if (close(fd) == -1 ){
printf("Error,Can't close the sourcefile");
return -1;
}
if (close(fd1) == -1 ){
printf("Error,Can't close the destfile");
return -1;
}
printf("Successn");
return 0;
}
|
if((fd1 = open(destfile,O_CREAT,S_IRWXU)) == -1){
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
没有指定打开模式,改为
if((fd1 = open(destfile,O_CREAT|O_RDWR,S_IRWXU))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
没有指定打开模式,改为
if((fd1 = open(destfile,O_CREAT|O_RDWR,S_IRWXU))