Simply open text file and read string lines

I’m a high-level application developer coming from a Perl, PHP - based language. I’ve touched C many times and I learned a lot via large bite-sized tasks, but I am no C programmer having no style and knowing no standards. Despite what I think I know, I have run into this task multiple times in my life and each time I forget how I did it before. I also have a heck of a time finding the answer by searching, despite how common this subject is.

As embarrassing as it is, here is my dilemma:

I am opening a text file on an SD device, reading in the entire line as a char array and then sending it through a processing function. My problem is reading the lines of different sizes into a char array.

example psuedo code:

#include <SD.h>
...
File myFile= SD.open("example.txt");
...

char* LineFromFile[255]; // what if line has 260 chars?

char c; // character read in from file
int n = 0; // the character counter

while (myFile.available()) {
  // retrieve next character in the line
  c = myFile.read();

  // if this is not a newline char, store and move on
  if (c != '\n') {
    LineFromFile[n] = c;
    n++;

  // we reached end of the line, process what we found
  } else {
    // this works fine for now
    processLine(LineFromFile, n);

    // reset counter
    n = 0; 

    // How to resize/reset LineFromFile[] ?

  }

}

Some more common (related) functions are not included in AVR-Lib that I know about (fopen, etc).

What is the best way to write this for an Arduino sketch as well as solving the problems I identified in the comments provided?

I’ve searched for this but everything I found seems to be a task that differs from this slightly making a different solution compared to my situation. I have had so much trouble over the years with this details to this seemingly simple operation. I need a C class or something…

So except for the size of LineFromFile it works?

You can do this two ways

a) Allocated enough memory for the longest expected line. b) Use malloc to grow the space as required.

b) is not really recommended on an embedded micro. So the only option I can see is to allocate enough RAM for the longest string.

If you don't know what that will be then you may have to read in say 100-byte chunks and process that before moving on.

It depends a lot on the nature of the data and the processing.


Rob

char* LineFromFile[255]; // what if line has 260 chars?

What if it does? This declaration is for an array of pointers to chars, not for an array of chars. They are not the same thing.