我是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();
}
可以使用类File的方法,如seek
和position
,也可以使用类File的基类方法,如find
。
方法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");
}
这里有一个更快的方法,读取整个文件在处理大文件时可能会相当慢。
// 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;
}
用法:
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.
}
}