当前位置:   article > 正文

linux系统编程—文件编程—Read操作编程_linux中先malloc,然后read代码怎么写

linux中先malloc,然后read代码怎么写

参数说明

终端下输入man 2 read查看头文件与相关参数

man 2 read
  1. //头文件
  2. #include <unistd.h>
  3. //参数信息
  4. ssize_t read(int fd, void *buf, size_t count);

fd:需要写入文件的文件描述符

buf:缓冲区,用于存放读取的内容

count:要读取的字节大小

返回值

读取失败:返回值为-1;

读取成功:返回读取内容的字节数。(返回值不一定等于count,而是实际所读取的值)

代码示例

  1. #include <stdio.h>
  2. //以下是man手册查询的头文件
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. //strlen头文件
  8. #include <string.h>
  9. //malloc头文件
  10. #include <stdlib.h>
  11. int main()
  12. {
  13. int fd;//定义与open函数返回值相同的int型,便于接受返回值
  14. char *buf = "writeabcdefghijklmn";
  15. fd = open("./file1",O_RDONLY);//以只读的方式打开本目录下的file1文件
  16. if(fd == -1) //如果没打开 返回值为-1(肯定打不开,因为没创建)
  17. {
  18. printf("open file1 failed\n");//终端输出打开file1失败
  19. fd = open("./file2",O_CREAT|O_RDWR,0600);//如果不存在则创建以可读可写模式 权限为0600
  20. if(fd > 0)
  21. {
  22. printf("open file2 successful\n");//终端输出打开file2成功
  23. printf("fd = %d\n",fd);//查看返回值
  24. }
  25. }
  26. int n_write = write(fd,buf,strlen(buf));//用strlen计算buf大小
  27. char *readbuf;
  28. //开辟空间
  29. readbuf = (char *)malloc(sizeof(char)*n_write + 1);
  30. //清理资源之后重新打开 刷新指针光标在文件头部
  31. close(fd);
  32. //以可读可写方式打开
  33. fd = open("./file2",O_RDWR);
  34. //要读取的大小设置为100 查看返回值是实际读取数还是count
  35. int n_read = read(fd,readbuf,100);
  36. printf("read:%d,countext:%s\n",n_read,readbuf);
  37. close(fd);//资源清理
  38. return 0;
  39. }

编译运行


打开file2文件,可以看到指针光标在头部,如果不close(fd)重新open而是直接读取,将读取失败

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/183070
推荐阅读
相关标签
  

闽ICP备14008679号