You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.0KB

  1. // Demo of fgets function to read lines from a file.
  2. #include <SPI.h>
  3. #include <SdFat.h>
  4. // SD chip select pin
  5. const uint8_t chipSelect = SS;
  6. SdFat sd;
  7. // print stream
  8. ArduinoOutStream cout(Serial);
  9. //------------------------------------------------------------------------------
  10. // store error strings in flash memory
  11. #define error(s) sd.errorHalt(F(s))
  12. //------------------------------------------------------------------------------
  13. void demoFgets() {
  14. char line[25];
  15. int n;
  16. // open test file
  17. SdFile rdfile("FGETS.TXT", O_READ);
  18. // check for open error
  19. if (!rdfile.isOpen()) error("demoFgets");
  20. cout << endl << pstr(
  21. "Lines with '>' end with a '\\n' character\n"
  22. "Lines with '#' do not end with a '\\n' character\n"
  23. "\n");
  24. // read lines from the file
  25. while ((n = rdfile.fgets(line, sizeof(line))) > 0) {
  26. if (line[n - 1] == '\n') {
  27. cout << '>' << line;
  28. } else {
  29. cout << '#' << line << endl;
  30. }
  31. }
  32. }
  33. //------------------------------------------------------------------------------
  34. void makeTestFile() {
  35. // create or open test file
  36. SdFile wrfile("FGETS.TXT", O_WRITE | O_CREAT | O_TRUNC);
  37. // check for open error
  38. if (!wrfile.isOpen()) error("MakeTestFile");
  39. // write test file
  40. wrfile.print(F(
  41. "Line with CRLF\r\n"
  42. "Line with only LF\n"
  43. "Long line that will require an extra read\n"
  44. "\n" // empty line
  45. "Line at EOF without NL"
  46. ));
  47. wrfile.close();
  48. }
  49. //------------------------------------------------------------------------------
  50. void setup(void) {
  51. Serial.begin(9600);
  52. while (!Serial) {} // Wait for Leonardo
  53. cout << pstr("Type any character to start\n");
  54. while (Serial.read() <= 0) {}
  55. delay(400); // catch Due reset problem
  56. // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  57. // breadboards. use SPI_FULL_SPEED for better performance.
  58. if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();
  59. makeTestFile();
  60. demoFgets();
  61. cout << pstr("\nDone\n");
  62. }
  63. void loop(void) {}