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.

93 Zeilen
2.3KB

  1. // Demo of rewriting a line read by fgets
  2. #include <SPI.h>
  3. #include <SdFat.h>
  4. // SD card chip select pin
  5. const uint8_t chipSelect = SS;
  6. // file system
  7. SdFat sd;
  8. // print stream
  9. ArduinoOutStream cout(Serial);
  10. //------------------------------------------------------------------------------
  11. // store error strings in flash memory
  12. #define error(s) sd.errorHalt(F(s))
  13. //------------------------------------------------------------------------------
  14. void demoFgets() {
  15. char line[25];
  16. int c;
  17. uint32_t pos;
  18. // open test file
  19. SdFile rdfile("FGETS.TXT", O_RDWR);
  20. // check for open error
  21. if (!rdfile.isOpen()) error("demoFgets");
  22. // list file
  23. cout << pstr("-----Before Rewrite\r\n");
  24. while ((c = rdfile.read()) >= 0) Serial.write(c);
  25. rdfile.rewind();
  26. // read lines from the file to get position
  27. while (1) {
  28. pos = rdfile.curPosition();
  29. if (rdfile.fgets(line, sizeof(line)) < 0) {
  30. error("Line not found");
  31. }
  32. // find line that contains "Line C"
  33. if (strstr(line, "Line C"))break;
  34. }
  35. // rewrite line with 'C'
  36. if (!rdfile.seekSet(pos))error("seekSet");
  37. rdfile.println("Line R");
  38. rdfile.rewind();
  39. // list file
  40. cout << pstr("\r\n-----After Rewrite\r\n");
  41. while ((c = rdfile.read()) >= 0) Serial.write(c);
  42. // close so rewrite is not lost
  43. rdfile.close();
  44. }
  45. //------------------------------------------------------------------------------
  46. void makeTestFile() {
  47. // create or open test file
  48. SdFile wrfile("FGETS.TXT", O_WRITE | O_CREAT | O_TRUNC);
  49. // check for open error
  50. if (!wrfile.isOpen()) error("MakeTestFile");
  51. // write test file
  52. wrfile.print(F(
  53. "Line A\r\n"
  54. "Line B\r\n"
  55. "Line C\r\n"
  56. "Line D\r\n"
  57. "Line E\r\n"
  58. ));
  59. wrfile.close();
  60. }
  61. //------------------------------------------------------------------------------
  62. void setup(void) {
  63. Serial.begin(9600);
  64. while (!Serial){} // wait for Leonardo
  65. cout << pstr("Type any character to start\n");
  66. while (Serial.read() <= 0) {}
  67. delay(400); // catch Due reset problem
  68. // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  69. // breadboards. use SPI_FULL_SPEED for better performance.
  70. if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();
  71. makeTestFile();
  72. demoFgets();
  73. cout << pstr("\nDone\n");
  74. }
  75. void loop(void) {}