Reading data from sd card with specified extension

Hello, I want to read a specific string from several other that are in a file inside the sd card. My data format is such that each data is written in a separate line and has its own extension :

D1|test N1
D2|test N2
D3|test N3
D4|test N4
D5|test N5
D6|test N6
D7|test N7

I want to read the data in D5
My output should look like this:

test N5

What have you tried ?

For instance, can you open the file, read it and print the line of data ?

yes, I understand the library example itself but I can't extract a particular data from other data

I would read the whole of each line into a C style string (a zero terminated array of chars) then test whether the first 2 characters match what you are looking for and, if so, print the rest of the string

Let's do one more thing, how can I read a specific line from among other lines? (end of line has \n)

I want to try to look for the index character, then read the characters after it until the end of the line, I have no idea how to move the cursor after the index character:

  while (Serial.available() > 0) {
    char input = Serial.read();

    if (input == 'S') {
      String myinput = Serial.readStringUntil('\n');

      if (SD.exists("data.txt")) {
        Serial.println("data.txt exists.");
        myFile = SD.open("data.txt");
        
        **if (myFile.find(myinput)) {**
          
        **}**
      } else {
        Serial.println("data.txt doesn't exist.");
        myFile = SD.open("data.txt", FILE_WRITE);
        myFile.close();
      }
    }
  }

Possible ONLY if all lines are the same length. If so, you can compute the position of the line in your file and use "seek" to position at that spot.

Could you write an example?

Start with something like this

#include <SD.h>
#include <SPI.h>

File file;
char line[100];

void setup()
{
  Serial.begin(115200);
  if (!SD.begin(4))
  {
    Serial.println(F("begin error"));
    while (1);
  }
  Serial.println(F("begin success"));
  readFile();
}

void loop()
{
}

boolean readLine()
{
  byte index = 0;
  while (file.available())
  {
    char inChar = file.read();
    if (inChar == '\n')
    {
      return false;
    }
    else
    {
      line[index++] = inChar;
      line[index] = '\0';
    }
  }
  return true;
}

void readFile()
{
  file = SD.open("test.txt", FILE_READ);
  if (!file)
  {
    Serial.println(F("error opening file"));
    while (1);
  }
  if (file)
  {
    Serial.println(F("open success"));
    boolean finished = false;
    while (!finished)
    {
      finished = readLine();
      Serial.println(line);
    }
    file.close();
  }
}

The line of data will be in the line string and can be parsed using the strtok() function

Can you search for examples of using "seek"?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.