2013-04-29 82 views
-2

我有以下代码从另一个模块获取文件路径,打开文件并读取内容。该文件正在打开,但读取失败并显示错误:文件编号错误。然后我打开后插入了一个写命令,该命令正常工作,但读取仍然失败。可以请某人告诉我为什么读取不起作用?此外,林困惑为什么写()甚至工作时,即时通讯模式打开文件。写入工作,但读取失败 - C

  char* file_content = (char*) malloc (1024); 
      int fd = open(filepath,"O_RDONLY"); 
      printf("I have attempted open file \n"); 
      fflush(stdout); 
      bzero(file_content, 1024*sizeof(char)); 
      if(fd <= 0) { //open failed 
      file_content = "Error opening file"; 
      printf("The error number is %d\n", errno); 
      fflush(stdout); 
      } 
      else 
      { 
      if(write(fd, "hello", 5)<0){ 
       printf("write failed"); 
       fflush(stdout); 
       } 
      if(read(fd, file_content,1023) < 0){ 
       printf("Error! Read file as %d\n",errno); 
       fflush(stdout); 
      } 
      } 

输出错误!将文件读取为8. 8 =错误的文件编号。请帮忙吗?

+4

'open(filepath,“O_RDONLY”);' - 您最需要阅读'open()'的手册页。 – 2013-04-29 20:15:56

+0

'(char *)malloc(1024)' - 你最需要阅读[这个答案的推理](http://stackoverflow.com/questions/605845/do-i-cast-the-result -of-malloc/605858#605858)关于该多余演员的有害性质。 – 2013-04-29 20:17:02

+1

这究竟是如何编译的?! – JustSid 2013-04-29 20:18:12

回答

3

问题是

open(filepath,"O_RDONLY"); 

应该

open(filepath, O_RDONLY); 

目前它使用字符串文字作为开旗的整数的地址。

+0

谢谢!我的错。 – 2013-04-29 20:33:47