// Function to read a text file one field at a time.
//
#include <SPI.h>
#include <SD.h>
#define CS_PIN BUILTIN_SDCARD
File file;
/*
* Read a file one field at a time.
*
* file - File to read.
*
* str - Character array for the field.
*
* size - Size of str array.
*
* delim - String containing field delimiters.
*
* return - length of field including terminating delimiter.
*
* Note, the last character of str will not be a delimiter if
* a read error occurs, the field is too long, or the file
* does not end with a delimiter. Consider this an error
* if not at end-of-file.
*
*/
size_t readField(File* file, char* str, size_t size, char* delim) {
char ch;
size_t n = 0;
while ((n + 1) < size && file->read(&ch, 1) == 1) {
// Delete CR.
if (ch == '\r') {
continue;
}
str[n++] = ch;
if (strchr(delim, ch)) {
break;
}
}
str[n] = '\0';
return n;
}
//------------------------------------------------------------------------------
#define errorHalt(msg) {Serial.println(F(msg)); while(1);}
//------------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
// Initialize the SD.
if (!SD.begin(CS_PIN)) errorHalt("begin failed");
// Create or open the file.
file = SD.open("/00000002", FILE_WRITE);
if (!file) errorHalt("open failed");
// Rewind file so test data is not appended.
file.seek(0);
// Write test data.
file.print(F(
"1,2,3\r\n"
"4,5,6\r\n"
"7,8\r\n" // missing a field
"9,10,11\r\n"
"12,13,14" // no delimiter
));
// Rewind the file for read.
file.seek(0);
size_t n; // Length of returned field with delimiter.
char str[20]; // Must hold longest field with delimiter and zero byte.
int _value = 0;
// Read the file and print fields.
while (true) {
n = readField(&file, str, sizeof(str), ",\n");
// done if Error or at EOF.
if (n == 0) break;
// Remove the delimiter.
str[n-1] = 0;
_value = int(str); //this should match the other
// Print the field.
Serial.println(str); //it doesn't
Serial.println(_value);
}
file.close();
}
//------------------------------------------------------------------------------
void loop() {
}