Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
8 years, 1 month ago.
About read data from SD .txt
Hi, all. Thanks for watching my question. i use LPC4088 board. i have an question about read data from SD .txt Take an example.This is my code.
int main(){ mkdir("/sd/MMA", 0777); sensorA(); } void sensorA(){ //Because it's just an example so i don't type my code //when the sensorA read the data so i printf it to SD .txt FILE *fp = fopen("/sd/MMA/MMAdata.txt", "a"); fprintf(fp,"%.2f\t",xd*180.0/PI); fprintf(fp,"%.2f\t",yd*180.0/PI); fprintf(fp,"%.2f\r\n",zd*180.0/PI); fclose(fp); }
And the txt. i insert my SD to computer.It can show like this. 0.91 -0.91 1.29 is the first data. 0.88 -0.88 1.25 is the second data. and so on. It is possible to read it like array and save them to buffer ? Thx very much!
1 Answer
8 years, 1 month ago.
Yes, that's fairly easy if the format of the file is always going to be exactly the same.
fscanf is probably the easiest method to do this:
float x[100],y[100],z[100]; int dataPtr = 0; int readFile() { FILE *fp = fopen("/sd/MMA/MMAdata.txt", "r"); while (!eof(fp) && (dataPtr<100)) { fscanf(fp,"%f\t%f\t%f\r\n",x[dataPtr],y[dataPtr],z[dataPtr]); dataPtr++; } fclose(fp); return dataPtr; }
If you need to cope with formats that aren't quite so fixed then read the input byte by byte into a char[] until you reach a \n. Replace the \n with 0 (c uses 0 to end strings not a new line) and then use strtok() to split the line into fields based on a separator charactor, tab in this case.