为什么写文件报错write(fd1,buf,count) ,errno 是9 EBADF,代码如下

wolfza 2003-04-08 05:21:10
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<stdio.h>
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<comand> [two parameter]");
return -1;
}
sourcefile = argv[1];
destfile = argv[2];
printf("source file is %s\n",sourcefile);
printf("dest file is %s\n",destfile);
if((fd1 = open(destfile,O_CREAT,S_IRWXU)) == -1){
printf("Open Error\n Error No= %d\n",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 %d\n",sizeof(buf));
while (( count = read(fd,buf,sizeof(buf)))>0)
{
if (write(fd1,buf,count) != count) //write 后出错
printf("error No=%d\n",errno);
printf("write data error\n");
}
if (count == -1)
printf("read data error");
else
{
printf("Success\n");
}
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("Success\n");
return 0;
}
...全文
1616 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
Ernestxiao 2010-06-05
  • 打赏
  • 举报
回复
ddddddddddddddddddddddddddddddddddd
wolfza 2003-04-09
  • 打赏
  • 举报
回复
thanks I know
ari 2003-04-09
  • 打赏
  • 举报
回复
我的DESTFILE 是新创建的,我设定mode 为 S_IRWXU,即文件属主具有可读写执行权限了,为何要加O_RDWR
^^^^^^^^^^^^^^^^^^^
指的是open/write/read时,用O_RDWR模式有权限。
好好理解一下。
你有这个权利,但你不用,还是没有的。
ari 2003-04-09
  • 打赏
  • 举报
回复
blh(老猫)
fd = open(sourcefile,O_RDONLY))
你用的是只读方式,当然不能写了,呵呵
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
呵呵他不是写这个fd的。
注意:
if (write(fd1,buf,count) != count) //write 后出错
wolfza 2003-04-09
  • 打赏
  • 举报
回复
我的DESTFILE 是新创建的,我设定mode 为 S_IRWXU,即文件属主具有可读写执行权限了,为何要加O_RDWR
blh 2003-04-09
  • 打赏
  • 举报
回复
fd = open(sourcefile,O_RDONLY))
你用的是只读方式,当然不能写了,呵呵
ari 2003-04-09
  • 打赏
  • 举报
回复
if((fd1 = open(destfile,O_CREAT,S_IRWXU)) == -1){
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
没有指定打开模式,改为
if((fd1 = open(destfile,O_CREAT|O_RDWR,S_IRWXU)) <0){

wolfza 2003-04-09
  • 打赏
  • 举报
回复
我在出错的地方写有注释
cenlmmx 2003-04-08
  • 打赏
  • 举报
回复
up
wolfza 2003-04-08
  • 打赏
  • 举报
回复
刷新

23,216

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧