Arduino File.write()

Description

The File.write() function writes data to the file.

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

Syntax

file.write(data)

file.write(buf, len)

Parameters

  • file: an instance of the File class that is returned by SD.open()
  • data: the byte, char, or string (char *) to write
  • buf: an array of characters or bytes
  • len: the number of elements in buf

Returns

  • Returns the number of bytes written

Example Code

/* * Created by ArduinoGetStarted.com * * This example code is in the public domain * * Tutorial page: https://arduinogetstarted.com/reference/library/arduino-file.write */ #include <SD.h> #define PIN_SPI_CS 4 File file; char buf[] = "Arduino"; 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: } SD.remove("arduino.txt"); // delete the file if existed // create new file by opening file for writing file = SD.open("arduino.txt", FILE_WRITE); if (file) { file.write('H'); // a character file.write('i'); // a character file.write('\n'); // new line file.write(buf, 7); file.close(); } else { Serial.print(F("SD Card: error on opening file arduino.txt")); } } void loop() { }

After running the above code, if you disconnect SD Cart from Arduino and connect the SD Card to your your PC, you will see a arduino.txt file with the below content

Hi Arduino

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