9 years, 6 months ago.

How to read integer values from SD Card while increasing it by one

Hi, I am writing some files to SD Card which are numbered using while(1) loop. The file name increments every time by one. Now I need that number to remain the same when my system gets reset so I am storing this integer value in a different file in SD Card and reading the data ( which is the last integer value for which my file was named) and then entering into while(1) loop. Now the problem is that it works until the integer value reaches 9, and then instead of going 10, it becomes 1. what could be the issue? Please suggest. Thanks in Advcance

2 Answers

9 years, 6 months ago.

A few things come to mind -

  • If you have a simple example in code, perhaps you could update your question (be sure to wrap the code with <<code>> <</code>> tags).
  • Are you reading the value from the tracking file, or are you reading a single digit?
  • Instead of keeping an extra file, you might read the directory on startup, and then find what files exist, thus avoiding the possibility of getting out of sync.

I read single values and every time value read is decimal of ASCII equivalent of the number. deducted 48 (ASCII 0 decimal equivalent) to get original number. Got it using b=b*10+fgetc(fp); thanks for the reply

posted by Fahd Ansary 05 Oct 2014
9 years, 6 months ago.

I'm with David, rather than use second file just look for the first unused file name. It may take a little longer if you have a lot of files but it'll avoid the risk of things getting out of sync.

int findNextFile() {

FILE *fp;
char fname[64];
int fileNumber;

snprintf(fname,64,"/sd/myFile%04d.txt",fileNumber); // change to match your file name structure

fp = fopen(fname,"r");

while (fp) {
  fclose(fp);
  fileNumber++;
  fp = fopen(fname,"r");
}

return fileNumber;
}