+ -
当前位置:首页 → 问答吧 → [问]open开O_DIRECT标志位,调用write出错.

[问]open开O_DIRECT标志位,调用write出错.

时间:2010-09-15

来源:互联网

  1. #include <stdio.h
  2. #include <sys/time.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <malloc.h>

  8. int main()
  9. {
  10.       char *buf = NULL;
  11.       int fd = -1, ret = -10;
  12.       buf = valloc(4100);
  13.       printf("buf address = %p\n", buf);

  14.       buf = "12345\n";
  15.       printf("the buf is:%s\n",buf);
  16.   
  17.       fd = open("/home/zhangqi/deadfish.txt", O_RDWR | O_DIRECT | O_CREAT);
  18.   
  19.       if (fd<0){
  20.           printf("Cannot open file\n");
  21.           exit(1);
  22.       }
  23.   
  24.       printf("fd = %d\n",fd);
  25.   
  26.       ret = write(fd, buf, 4096);
  27.       if (ret < 4096)
  28.           printf("write error!\n");
  29.   
  30.       printf("after write...\nret = %d\n",ret);

  31.       free(buf);
  32.       close(fd);
  33.       return 0;
  34. }
复制代码
运行的结果是:
  1. buf address = 0x804b000
  2. the buf is:12345

  3. fd = 3
  4. write error!
  5. after write...
  6. ret = -1
  7. Segmentation fault
复制代码
大伙帮忙看看。
要写的文件是生成了,但是内容没有写进去。。。

作者: almeydifer   发布时间: 2010-09-15

buf = valloc(4100);
      printf("buf address = %p\n", buf);

      buf = "12345\n";
      printf("the buf is:%s\n",buf);

这个是什么东西呀,你在哪见过这样设置的buf的么??

buf = "12345\n";后, buf的长度只有7了,你valloc的已经被你扔掉了。

你再去好好学习一下指针与数组哈。

作者: mekinglong   发布时间: 2010-09-15



QUOTE:
buf = valloc(4100);
      printf("buf address = %p\n", buf);

      buf = "12345\n";
      print ...
mekinglong 发表于 2010-09-15 13:09



搞定,您说的很对。

作者: almeydifer   发布时间: 2010-09-15



QUOTE:
#       buf = valloc(4100);
#       printf("buf address = %p\n", buf);
#

#       buf = "12345\n";


这样的代码,你确定那个字符串写入到你申请的那块内存了吗?

作者: Godbach   发布时间: 2010-09-15



QUOTE:
这样的代码,你确定那个字符串写入到你申请的那块内存了吗?
Godbach 发表于 2010-09-15 13:45



是的是的,稀里糊涂了。谢谢您。

作者: almeydifer   发布时间: 2010-09-15

热门下载

更多