Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

76 linhas
2.2KB

  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 <SdFat.h>
  10. // SD chip select pin
  11. const uint8_t chipSelect = SS;
  12. // file system object
  13. SdFat sd;
  14. // create a serial stream
  15. ArduinoOutStream cout(Serial);
  16. //------------------------------------------------------------------------------
  17. void makeTestFile() {
  18. ofstream sdout("GETLINE.TXT");
  19. // use flash for text to save RAM
  20. sdout << pstr(
  21. "short line\n"
  22. "\n"
  23. "17 character line\n"
  24. "too long for buffer\n"
  25. "line with no nl");
  26. sdout.close();
  27. }
  28. //------------------------------------------------------------------------------
  29. void testGetline() {
  30. const int line_buffer_size = 18;
  31. char buffer[line_buffer_size];
  32. ifstream sdin("GETLINE.TXT");
  33. int line_number = 0;
  34. while (sdin.getline(buffer, line_buffer_size, '\n') || sdin.gcount()) {
  35. int count = sdin.gcount();
  36. if (sdin.fail()) {
  37. cout << "Partial long line";
  38. sdin.clear(sdin.rdstate() & ~ios_base::failbit);
  39. } else if (sdin.eof()) {
  40. cout << "Partial final line"; // sdin.fail() is false
  41. } else {
  42. count--; // Don’t include newline in count
  43. cout << "Line " << ++line_number;
  44. }
  45. cout << " (" << count << " chars): " << buffer << endl;
  46. }
  47. }
  48. //------------------------------------------------------------------------------
  49. void setup(void) {
  50. Serial.begin(9600);
  51. while (!Serial) {} // wait for Leonardo
  52. // pstr stores strings in flash to save RAM
  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. // make the test file
  60. makeTestFile();
  61. // run the example
  62. testGetline();
  63. cout << "\nDone!\n";
  64. }
  65. //------------------------------------------------------------------------------
  66. void loop(void) {}