[英]Arduino read last line from SD Card
I am pretty new to Arduino business.我对 Arduino 业务还很陌生。 How do I read the last line from a SD Card?
如何从 SD 卡读取最后一行? With following code snippet I can read the first line (all characters before "\n").
使用以下代码片段,我可以阅读第一行(“\n”之前的所有字符)。 Now I would like to include a "backwards" statement (or something).
现在我想包括一个“向后”的声明(或其他)。
My code so far:到目前为止我的代码:
#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();
}
You can use methods of class File like seek
and position
and methods of base class for File the Stream class , for example method find
.您可以使用File 类的方法,例如
seek
和position
以及 File Stream 类的基类方法,例如方法find
。
Method seek
sets the reading or writing position for the opened file.方法
seek
设置打开文件的读取或写入位置。
File file = SD.open("datalog.txt");
if (file) {
uint32_t lineStart = 0;
while (file.available()) {
lineStart = file.position();
if (!file.find((char*) "\n"))
break;
}
file.seek(lineStart);
while (file.available()) {
Serial.write(file.read());
}
file.close();
} else {
Serial.println("error opening datalog.txt");
}
Here a faster method, reading the whole file can be quite slow when dealing with large files.这是一种更快的方法,在处理大文件时读取整个文件可能会很慢。
// rewinds the file to the last occurrence of char c.
// returns 0 on error
int reverseFind(File& f, char c)
{
for(unsigned long pos = f.position(); pos != 0 && f.seek(pos); --pos)
{
int rd = f.peek();
if (rd < 0)
return 0;
// found!
if (rd == (c & 0xFF))
return 1;
}
return (f.peek() == (c & 0xFF));
}
// seeks to the beginning of th elast line in the file.
// returns 0 on error.
int seekLastLine(File& f)
{
if (!file.seek(f.size() - 2)) // -2 because last line could have a line ending..
return 0;
// find end of previous line.
if (reverseFind(f, '\n'))
return (f.read() != -1); // move forward to beginning of line
// if we're at beginning of file, then the first line is the last line.
if (f.position() == 0)
return 1;
// we should logically never reach unless there was some I/O error.
return 0;
}
Usage:用法:
File f;
char buf[32];
if (seekLastLine(f))
{
unsigned long len = f.size() - f.position();
if (len > 32)
{
// ERROR! our read buffer is too small.
}
else if (!f.read(buf, len))
{
// deal with/log I/0 error...
}
else
{
// do something with line of data in buf.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.