ArduinoCore-API icon indicating copy to clipboard operation
ArduinoCore-API copied to clipboard

ANSI-C-like fprintf(), fscanf()

Open shiftleftplusone opened this issue 10 years ago • 2 comments

Urgently needed: ANSI-C-like fprintf(), fscanf()

Actually homebrewed fprintf_ works fine (SD file checked on PC), just fscanf_ muddles all up.

Up to now I've used a homebrewed function fscanf_ but it doesn't work for floats in larger files (>400 elements), neither by 1.6.1 nor by 1.6.3 nor by 1.6.5.

These are the homebrewed functions:

Code:

//*******************************************************************************_​**_********
int32_t  fscanf_ ( File \* stream, const char fmtstr[], ... ) {
   const  int32_t   MAXSTRSIZE = 1024;
   char   str[MAXSTRSIZE];
   va_list   args;
   int32_t   i=0, cnt=0;
   int16_t   chr;

   va_start(args, fmtstr);

   strcpy(str, "");
   while ( (stream->available()) && (i < MAXSTRSIZE-1) ) {  
      chr = stream->read() ;
      if (chr>=0 && chr!='\n') {
           str[i]=(char)chr;  
           ++i;
      }
      else break;  
   }

   str[++i] = '\0';

   cnt = vsscanf( str, fmtstr, args );
   va_end(args);

   return cnt;
}

//*******************************************************************************_​**_********

int32_t fprintf_ ( File \* stream, const char fmtstr[], ... ) {
   char      str[1024];
   va_list   args;
   int32_t   num;

   va_start( args, fmtstr );
   num = vsnprintf(str, sizeof(str), fmtstr, args);
   stream->print(str);
   va_end( args );

   return num;
}

//*******************************************************************************_​**_********

shiftleftplusone avatar Jun 21 '15 09:06 shiftleftplusone

Maybe this thread is worthy: https://groups.google.com/a/arduino.cc/forum/#!topic/developers/7KpdLDgFsO0

q2dg avatar Jun 21 '15 14:06 q2dg

I don't understand unfortunately how in your topic they can read and write strings sequentially from an SD file and convert it to int or float. There also are no Arduino SD class functions available like, e.g., SD.freadFloat() or SD.freadDouble() or SD.freadInt16() or SD.freadInt32(). In principle, a file system plus ANSI C stdio.h functionality would be best (i.e., fprintf, fscanf) because they work with standard format strings ("%f %d %ld" ) both for writing to and reading from an SD file.

shiftleftplusone avatar Jun 21 '15 17:06 shiftleftplusone