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.

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