選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

fgets.ino 2.0KB

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