readwrite_sample.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. #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. rt_kprintf("Write done.\n");
  29. }
  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. rt_kprintf("Read from file test.txt : %s \n", buffer);
  37. if (size < 0)
  38. return ;
  39. }
  40. }
  41. /* 导出到 msh 命令列表中 */
  42. MSH_CMD_EXPORT(readwrite_sample, readwrite sample);