从SD卡中读取Arduino的最后一行

3

我对Arduino还比较新。如何读取SD卡中的最后一行?使用以下代码片段,我可以读取第一行("\n"前的所有字符)。现在我想包含一个“向后”语句(或其他方式)。

目前我的代码:

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

File SD_File;

int pinCS = 10;

char cr;


void setup() {
  Serial.begin(9600);
  SD.begin();

  SD_File = SD.open("test.txt", FILE_WRITE);  
  SD_File.println("hello");
  SD_File.close();

  SD_File = SD.open("test.txt");
  while(true){
    cr = SD_File.read();
    if((cr == '\n') && ("LAST LINE?"))
        break;
    Serial.print(cr);
    }
  SD_File.close();

}

void loop() {

}

非常感谢您的帮助。


1
你的问题不够清晰。你是在寻找available()还是peek()?请注意,最后一行不一定以\n结尾。 - zdf
2个回答

1

我不确定我理解了你的问题。

  • "如何实现seekg?" 没有seekg。但是,有一个seek
  • 是SD库的文档页面。在页面的右侧,有一个File类方法的列表(包括seek等)。
  • "如何读取最后一行..." 你的代码中没有读取行。如果你只想到达文件末尾,请使用:SD_File.seek( SD_File.size() ); 如果你想读取最后一行,最简单的方法是编写一个getline函数,并逐行读取整个文件直到结束。假设MAX_LINE足够大并且getline在成功时返回零:

//...
char s[ MAX_LINE ];
while ( getline( f, s, MAX_LINE , '\n' ) == 0 )
  ;

// when reaching this point, s contains the last line
Serial.print( "This is the last line: " );
Serial.print( s );

这是一个关于编程的内容,以下是翻译文本:

这里有一个关于getline的想法(无保证 - 未经测试):

/*
  s     - destination
  count - maximum number of characters to write to s, including the null terminator. If 
          the limit is reached, it returns -2.
  delim - delimiting character ('\n' in your case)

  returns:
     0 - no error
    -1 - eof reached
    -2 - full buffer
*/
int getline( File& f, char* s, int count, char delim )
{
  int ccount = 0;
  int result = 0;
  if ( 0 < count )
    while ( 1 )
    {
      char c = f.peek();
      if ( c == -1 )
      {
        f.read(); // extract
        result = -1;
        break;  // eof reached
      }
      else if ( c == delim )
      {
        f.read(); // extract
        ++ccount;
        break; // eol reached
      }
      else if ( --count <= 0 )
      {
        result = -2;
        break; // end of buffer reached
      }
      else
      {
        f.read(); // extract
        *s++ = c;
        ++ccount;
      }
    }

  *s = '\0'; // end of string
  return ccount == 0 ? -1 : result;
}

1

由于您在技术上打开文本文件,因此可以使用seekg跳转到文件末尾并读取最后一行,如答案中所述。

如果这不太有用,添加更多的上下文和示例文件将有助于我们更好地理解您的问题。


谢谢你的回答。我该如何实现seekg?它属于哪个库?当我尝试在我的DUE上上传代码时,它只会给出错误。 - Artur Müller Romanov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接