【问题标题】:Arduino read last line from SD CardArduino 从 SD 卡读取最后一行
【发布时间】:2018-06-26 12:54:44
【问题描述】:

我对 Arduino 业务很陌生。如何从 SD 卡中读取最后一行?使用以下代码 sn-p 我可以读取第一行(“\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() {

}

非常感谢您的帮助。

【问题讨论】:

  • 您的问题不清楚。您在寻找available() 还是peek()?请注意,最后一行不一定以 \n 结尾。

标签: c++ arduino sd-card


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答。如何实现 seekg?它属于哪个图书馆?当我尝试在我的 DUE 上上传代码时,它只给出错误。
【解决方案2】:

我不确定我是否理解你的问题。

  • “我如何实现seekg?” 没有seekg。但是,有一个seek
  • This 是 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;
}

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多