Arduino File.read()

Description

The File.read() function reads a byte or a number of bytes to from the file to buffer.

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

Syntax

file.read()

file.read(buf, len)

Parameters

  • File: an instance of the File class that is returned by SD.open()
  • Buf: an array of characters or bytes
  • Len: the number of elements in buf

Returns

  • The next byte (or character), or -1 if none is available.

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.read */ #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) { int rlen = file.available(); char ch = file.read(); // read the first character file.read(buf, rlen - 1); // read the remaining to buffer Serial.print(ch); Serial.print(buf); file.close(); } else { Serial.print(F("SD Card: error on opening file")); } } void loop() { }
  • Open Serial Monitor, you will see as below:
Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
Hi Arduino
Ln 11, Col 1
Arduino Uno on COM15
2

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables .

※ OUR MESSAGES