reading only the first character in a line on the SD card

Here is a sketch that demonstrates counting lines.

#include <SD.h>
#define BUF_DIM 32
#define CHIP_SELECT 10
File file;
//-------------------------------------------------------
uint32_t lineCount(File* f) {
  char buf[BUF_DIM];
  uint32_t nl = 0;
  int n;
  
  // rewind file
  f->seek(0);

  // count lines
  while ((n = f->read(buf, sizeof(buf))) > 0) {
    for (int i = 0; i < n; i++) {
      if (buf[i] == '\n') nl++;
    }
  }
  return nl;
}
//-------------------------------------------------------
void setup() {
  Serial.begin(9600);
  Serial.println("start");
  if (!SD.begin(CHIP_SELECT)) {
    Serial.println("begin error");
    return;
  }
  file = SD.open("TEST.TXT");
  if (!file) {
    Serial.println("open error");
    return;
  }
  uint32_t m = micros();
  uint32_t n = lineCount(&file);
  m = micros() - m;
  Serial.print(file.size());
  Serial.println(" bytes");
  Serial.print(n);
  Serial.println(" lines");
  Serial.print(m);
  Serial.println(" micros");
  Serial.println("done");  
}
void loop() {
}

Here is output from a test file:

start
9388 bytes
299 lines
53084 micros
done

It takes about 0.053 seconds with a 32 byte read buffer.

The time varies with buffer size. Here are other results:

One byte read buffer.

start
9388 bytes
299 lines
327632 micros
done

Ten read byte buffer.

start
9388 bytes
299 lines
72732 micros
done

100 byte read buffer.

start
9388 bytes
299 lines
47452 micros
done

1 Like