Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

112 Zeilen
2.4KB

  1. // Demo of rewriting a line read by fgets
  2. #include <SPI.h>
  3. #include "SdFat.h"
  4. #include "sdios.h"
  5. // SD card chip select pin
  6. const uint8_t chipSelect = SS;
  7. // file system
  8. SdFat sd;
  9. // print stream
  10. ArduinoOutStream cout(Serial);
  11. //------------------------------------------------------------------------------
  12. // store error strings in flash memory
  13. #define error(s) sd.errorHalt(F(s))
  14. //------------------------------------------------------------------------------
  15. void demoFgets() {
  16. char line[25];
  17. int c;
  18. uint32_t pos;
  19. // open test file
  20. SdFile rdfile("fgets.txt", O_RDWR);
  21. // check for open error
  22. if (!rdfile.isOpen()) {
  23. error("demoFgets");
  24. }
  25. // list file
  26. cout << F("-----Before Rewrite\r\n");
  27. while ((c = rdfile.read()) >= 0) {
  28. Serial.write(c);
  29. }
  30. rdfile.rewind();
  31. // read lines from the file to get position
  32. while (1) {
  33. pos = rdfile.curPosition();
  34. if (rdfile.fgets(line, sizeof(line)) < 0) {
  35. error("Line not found");
  36. }
  37. // find line that contains "Line C"
  38. if (strstr(line, "Line C")) {
  39. break;
  40. }
  41. }
  42. // rewrite line with 'C'
  43. if (!rdfile.seekSet(pos)) {
  44. error("seekSet");
  45. }
  46. rdfile.println("Line R");
  47. rdfile.rewind();
  48. // list file
  49. cout << F("\r\n-----After Rewrite\r\n");
  50. while ((c = rdfile.read()) >= 0) {
  51. Serial.write(c);
  52. }
  53. // close so rewrite is not lost
  54. rdfile.close();
  55. }
  56. //------------------------------------------------------------------------------
  57. void makeTestFile() {
  58. // create or open test file
  59. SdFile wrfile("fgets.txt", O_WRONLY | O_CREAT | O_TRUNC);
  60. // check for open error
  61. if (!wrfile.isOpen()) {
  62. error("MakeTestFile");
  63. }
  64. // write test file
  65. wrfile.print(F(
  66. "Line A\r\n"
  67. "Line B\r\n"
  68. "Line C\r\n"
  69. "Line D\r\n"
  70. "Line E\r\n"
  71. ));
  72. wrfile.close();
  73. }
  74. //------------------------------------------------------------------------------
  75. void setup() {
  76. Serial.begin(9600);
  77. // Wait for USB Serial
  78. while (!Serial) {
  79. SysCall::yield();
  80. }
  81. cout << F("Type any character to start\n");
  82. while (!Serial.available()) {
  83. SysCall::yield();
  84. }
  85. // Initialize at the highest speed supported by the board that is
  86. // not over 50 MHz. Try a lower speed if SPI errors occur.
  87. if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
  88. sd.initErrorHalt();
  89. }
  90. makeTestFile();
  91. demoFgets();
  92. cout << F("\nDone\n");
  93. }
  94. void loop() {}