SD Card read length

Is there a way to know how many bytes or the "length" of the string within the text file located on an SD card?

So, you have a file on a sd card. Do you want to know the size of the file or the number of characters in it?

The library sd does have size-method which returns the size of the file in bytes.

number of chars in it.

Does that mean I have to read it twice? once to read every char and increment it until I close the file and the other to actually parse it later?

Isn't the size of the text file the number of characters in it?

You could simply save the text in the first place. As you said, read character at a time and increment a variable. Then append a string or String by the character. This way you got both results (but you have to think about returning the values since a function can only return 1 value).

But now that we are on this topic, you should also test if the actual file size in bytes is the same as the amount of characters in it. It should as far as I know.

I am testing on my local PC here, when I write a text file, and left blank, its 0 bytes. When I had 1 char, its 1 byte, 333 chars its 333 bytes. White space takes a byte.

Yes that makes sense. Good, now we know for sure.

You haven't been specfic on your objective, do you really need to know how many chars are in the file??

It would be much faster and easier to read a full line of data, and count the lines instead of characters, that could include no fixed length records.

I have a similar function for printing the last 14 lines of my SD Card logs to my display, and since I don't know the length of each line, nor the numbers of lines I read all the way to the end saving the position of the last 14 lines, and then get back to the saved positions reading and printing it's content...

Here is an example:

void readLogs() {
  byte line = 0;
  int position[15] = {};
  char data[64] = {};
  SdFile logFile(LOGS, O_CREAT | O_RDWR);
  if (logFile.isOpen()) {
    logFile.seekSet(position[line]);
    while (logFile.available()) {
      while (data[2] == '\0') {
        position[line] = logFile.curPosition();
        logFile.fgets(data, sizeof(data), "\n");
      }
      memset(data, 0, sizeof(data));
      if (line++ >= 14) line = 0;
    }
    for (byte string = 0; string < 15; string++) {
      logFile.seekSet(position[line]);
      logFile.fgets(data, sizeof(data), "\n");
      //print
      memset(data, 0, sizeof(data));
      if (line++ >= 14) line = 0;
    }
    logFile.close();
  }
}