Arduino File.readBytesUntil()

Description

The File.readBytesUntil() function reads characters from a file into a buffer. The function terminates if the terminator character is detected, the determined length has been read, or it times out (see setTimeout()). The function returns the characters up to the last character before the supplied terminator. The terminator itself is not returned in the buffer.

The File.readBytesUntil() function returns the number of bytes placed in the buffer. A 0 means no valid data was found.

The File.readBytesUntil() function inherits from the Stream utility class.

Syntax

file.readBytesUntil(character, buffer, length)

Parameter Values

  • file: an instance of a class that inherits from File.
  • character: the character to search for. Allowed data types: char.
  • buffer: the buffer to store the bytes in. Allowed data types: array of char or byte.
  • length: the number of bytes to read. Allowed data types: int.

Return Values

  • The number of bytes placed in the buffer.

Notes and Warnings

The terminator character is discarded from the return

Example Code

Create a arduino.txt file with the below content

Hi Arduino
/* * Created by ArduinoGetStarted.com * * This example code is in the public domain * * Tutorial page: https://arduinogetstarted.com/reference/library/arduino-file.readbytesuntil */ #include <SD.h> #define PIN_SPI_CS 4 File file; char buf[20]; void setup() { Serial.begin(9600); if (!SD.begin(PIN_SPI_CS)) { Serial.println(F("SD CARD FAILED, OR NOT PRESENT!")); while (1); // don't do anything more: } // open file for reading file = SD.open("arduino.txt", FILE_READ); if (file) { while (file.available()) { int max_len = file.available(); int read_len = file.readBytesUntil('\n', buf, max_len); // read to buffer to buffer, \n character is discarded from buffer Serial.print("LENGTH:"); Serial.println(read_len); Serial.println("CONTENT:"); Serial.println(buf); } file.close(); } else { Serial.print(F("SD Card: error on opening file")); } } void loop() { }
  • Open Serial Monitor, you will see as below:
COM6
Send
LENGTH:2 CONTENT: Hi LENGTH:7 CONTENT: Arduino
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES