免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1191 | 回复: 2
打印 上一主题 下一主题

[Linux] 这是为什么,write, read操作 [复制链接]

论坛徽章:
1
数据库技术版块每日发帖之星
日期:2015-08-23 06:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-10-12 20:32 |只看该作者 |倒序浏览
各位能帮我解答一下这是为什么吗?
  1. #include <fcntl.h>
  2. #include <unistd.h>
  3. #include <sys/stat.h>
  4. #include <stdio.h>

  5. struct student {
  6. int age;
  7. char name[20];
  8. };

  9. int main()
  10. {
  11.         int fd;        char buf[] = "hello world!\n";
  12.     struct student chen = {22, "Jeremy Chen"};
  13.     struct student chen_copy;
  14.     fd = open("test.txt", O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IWUSR | S_IRUSR);
  15.     write(fd, &chen, sizeof(chen));


  16.     printf("cur offset %d\n", lseek(fd, 0, SEEK_CUR));
  17.     lseek(fd, 0, SEEK_SET);
  18.     printf("cur offset %d\n", lseek(fd, 0, SEEK_CUR));
  19.     read(fd, &chen_copy, sizeof(chen_copy));
  20.     printf("chen_copy age:%d, name : %s\n", chen_copy.age, chen_copy.name);

  21. //    lseek(fd, 0, SEEK_SET);
  22. //    printf("cur offset %d\n", lseek(fd, 0, SEEK_CUR));
  23. //   
  24. //    read(fd, &chen_copy, sizeof(chen_copy));
  25. //    printf("cur offset %d\n", lseek(fd, 0, SEEK_CUR));
  26. //    printf("chen_copy age:%d, name : %s\n", chen_copy.age, chen_copy.name);
  27.         close(fd);
  28. }
复制代码
打开一个文件后,写内容,然后在保持打开的情况下将文件偏移置0,然后读刚写的内容。读不出来呢?
想了几天也没想出来,有人能帮我解释一下吗?

论坛徽章:
4
水瓶座
日期:2013-09-06 12:27:30摩羯座
日期:2013-09-28 14:07:46处女座
日期:2013-10-24 14:25:01酉鸡
日期:2014-04-07 11:54:15
2 [报告]
发表于 2012-10-12 21:25 |只看该作者
O_WRONLY  -> O_RDWR

论坛徽章:
1
数据库技术版块每日发帖之星
日期:2015-08-23 06:20:00
3 [报告]
发表于 2012-10-12 21:29 |只看该作者
回复 2# linux_c_py_php
刚试了一下,果然是这个问题!!
看来写程序一定要心细啊,谢谢了……


   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP