readwrite_sample.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. *
  9. */
  10. /*
  11. * 代码清单:文件读写例子
  12. *
  13. * 这个例子演示了如何读写一个文件。
  14. */
  15. #include <rtthread.h>
  16. #if RT_VER_NUM >= 0x40100
  17. #include <fcntl.h> /* 当需要使用文件操作时,需要包含这个头文件 */
  18. #else
  19. #include <dfs_posix.h>
  20. #endif /*RT_VER_NUM >= 0x40100*/
  21. static void readwrite_sample(void)
  22. {
  23. int fd, size;
  24. char s[] = "RT-Thread Programmer!", buffer[80];
  25. rt_kprintf("Write string %s to test.txt.\n", s);
  26. /* 以创建和读写模式打开 /text.txt 文件,如果该文件不存在则创建该文件*/
  27. fd = open("/text.txt", O_WRONLY | O_CREAT);
  28. if (fd >= 0)
  29. {
  30. write(fd, s, sizeof(s));
  31. close(fd);
  32. rt_kprintf("Write done.\n");
  33. }
  34. /* 以只读模式打开 /text.txt 文件 */
  35. fd = open("/text.txt", O_RDONLY);
  36. if (fd >= 0)
  37. {
  38. size = read(fd, buffer, sizeof(buffer));
  39. close(fd);
  40. rt_kprintf("Read from file test.txt : %s \n", buffer);
  41. if (size < 0)
  42. return ;
  43. }
  44. }
  45. /* 导出到 msh 命令列表中 */
  46. MSH_CMD_EXPORT(readwrite_sample, readwrite sample);