Skip to content

Arduino SD File Write Not Saving Data

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about Arduino SD File Write Not Saving Data. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Data written to an SD file is lost or the file is empty after writing.

Quick Fix

Wrong

File f = SD.open("data.txt", FILE_WRITE);
f.print("Hello");  // Data may not be flushed to card
File exists but is empty or truncated.
#include <SD.h>

void setup() {
  Serial.begin(9600);
  while (!Serial);
  
  if (!SD.begin(4)) {
    Serial.println("SD init failed");
    return;
  }
  
  File f = SD.open("data.txt", FILE_WRITE);
  if (f) {
    f.println("Line 1: sensor data");
    f.println("Line 2: 42");
    f.flush();  // Force write to card
    Serial.println("Data written and flushed");
    f.close();
  } else {
    Serial.println("Failed to open file");
  }
  
  // Verify
  f = SD.open("data.txt");
  if (f) {
    while (f.available()) {
      Serial.write(f.read());
    }
    f.close();
  }
}

void loop() { }
Data written and flushed
Line 1: sensor data
Line 2: 42

Prevention

Always f.close() after writing — close() flushes the buffer. For important data during logging, call f.flush() periodicaly (every N writes). FILE_WRITE opens for appending (starts at end of file). For overwrite, open in FILE_WRITE then f.seek(0).

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### Does SD.write() immediately write to the card?

No. Data is buffered in RAM (512 bytes). It is written to the card when the buffer is full, flush() is called, or close() is called.

What happens if power is lost during write?

The current 512-byte sector being written may be corrupted. The FAT may also be corrupted. Use f.sync() (same as flush()) periodicaly to minimize data loss.

Can I append to a file?

Yes. FILE_WRITE mode opens the file at the end. Every write appends. To overwrite, open with FILE_WRITE then call f.seek(0) before writing.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro