readwrite_sample.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. * Copyright (c) 2006-2018, 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. #include <dfs_posix.h> /* 当需要使用文件操作时,需要包含这个头文件 */
  17. static void readwrite_sample(void)
  18. {
  19. int fd, size;
  20. char s[] = "RT-Thread Programmer!", buffer[80];
  21. rt_kprintf("Write string %s to test.txt.\n", s);
  22. /* 以创建和读写模式打开 /text.txt 文件,如果该文件不存在则创建该文件*/
  23. fd = open("/text.txt", O_WRONLY | O_CREAT);
  24. if (fd >= 0)
  25. {
  26. write(fd, s, sizeof(s));
  27. close(fd);
  28. }
  29. rt_kprintf("Write done.\n");
  30. /* 以只读模式打开 /text.txt 文件 */
  31. fd = open("/text.txt", O_RDONLY);
  32. if (fd >= 0)
  33. {
  34. size = read(fd, buffer, sizeof(buffer));
  35. close(fd);
  36. if (size < 0)
  37. return ;
  38. }
  39. rt_kprintf("Read from file test.txt : %s \n", buffer);
  40. }
  41. /* 导出到 msh 命令列表中 */
  42. MSH_CMD_EXPORT(readwrite_sample, readwrite sample);