Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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