您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

85 行
2.3KB

  1. /*
  2. * Example of getline from section 27.7.1.3 of the C++ standard
  3. * Demonstrates the behavior of getline for various exceptions.
  4. * See http://www.cplusplus.com/reference/iostream/istream/getline/
  5. *
  6. * Note: This example is meant to demonstrate subtleties the standard and
  7. * may not the best way to read a file.
  8. */
  9. #include <SPI.h>
  10. #include "SdFat.h"
  11. #include "sdios.h"
  12. // SD chip select pin
  13. const uint8_t chipSelect = SS;
  14. // file system object
  15. SdFat sd;
  16. // create a serial stream
  17. ArduinoOutStream cout(Serial);
  18. //------------------------------------------------------------------------------
  19. void makeTestFile() {
  20. ofstream sdout("getline.txt");
  21. // use flash for text to save RAM
  22. sdout << F(
  23. "short line\n"
  24. "\n"
  25. "17 character line\n"
  26. "too long for buffer\n"
  27. "line with no nl");
  28. sdout.close();
  29. }
  30. //------------------------------------------------------------------------------
  31. void testGetline() {
  32. const int line_buffer_size = 18;
  33. char buffer[line_buffer_size];
  34. ifstream sdin("getline.txt");
  35. int line_number = 0;
  36. while (sdin.getline(buffer, line_buffer_size, '\n') || sdin.gcount()) {
  37. int count = sdin.gcount();
  38. if (sdin.fail()) {
  39. cout << "Partial long line";
  40. sdin.clear(sdin.rdstate() & ~ios_base::failbit);
  41. } else if (sdin.eof()) {
  42. cout << "Partial final line"; // sdin.fail() is false
  43. } else {
  44. count--; // Don’t include newline in count
  45. cout << "Line " << ++line_number;
  46. }
  47. cout << " (" << count << " chars): " << buffer << endl;
  48. }
  49. }
  50. //------------------------------------------------------------------------------
  51. void setup(void) {
  52. Serial.begin(9600);
  53. // Wait for USB Serial
  54. while (!Serial) {
  55. SysCall::yield();
  56. }
  57. // F stores strings in flash to save RAM
  58. cout << F("Type any character to start\n");
  59. while (!Serial.available()) {
  60. SysCall::yield();
  61. }
  62. // Initialize at the highest speed supported by the board that is
  63. // not over 50 MHz. Try a lower speed if SPI errors occur.
  64. if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) {
  65. sd.initErrorHalt();
  66. }
  67. // make the test file
  68. makeTestFile();
  69. // run the example
  70. testGetline();
  71. cout << "\nDone!\n";
  72. }
  73. //------------------------------------------------------------------------------
  74. void loop(void) {}