fseek bug if moving to end of file

14 Nov 2010

I think I found a bug in fseek in writable files. Once you fseek to the end of the file, subsequent fseeks (at least with SEEK_SET) ignore the offset and position to the beginning of the file. Unfortunately I haven't found a workaround yet, but this behaviour is necessary for random access files. Interestingly ftell returns the intended offset.

Is this a problem of the mbed implementation ?

Code to reproduce:

#include "mbed.h"

LocalFileSystem local("local");

int main()
{
FILE *fp;
char buff1[5] = "ABCD";
char buff2[5] = "WXYZ";
char buff3[3] = "01";

fp = fopen("/local/out.txt","w");
if(!fp)   printf("Error open file\r\n");
fwrite(buff1,1,4,fp);   // file is now "ABCD"       ->OK
fseek(fp,0,SEEK_END);   //seek to end
// same effect with: fseek(fp,4,SEEK_SET);
fwrite(buff2,1,4,fp);   // file is now "ABCDWXYZ"   ->OK

fseek(fp,3,SEEK_SET);  // this fseek sets fp to 0 instead of 3 !
fwrite(buff3,1,2,fp);  // file should now be "ABC01XYZ" but is "01"
fclose(fp);
return(0);
}

14 Nov 2010

Try "wb". AFAIR there can be issues with seeks in files opened in text mode.

14 Nov 2010 . Edited: 14 Nov 2010

Hi Andreas,

I just had a look at this. The LocalFileSystem talks to the mbed interface chip to get access to the mbed USB filesystem. The mbed interface is actually implemented using Keil RTX (a RTOS and Libraries), so I had a look at their spec for the filesystem. It has a note there that say "Seeking within a file opened for "w" mode is currently unsupported."; see http://www.keil.com/support/man/docs/rlarm/rlarm_fseek.htm

Assuming that is the case, this explains why the LocalFileSystem has this limitation. However, this is a limitation of the mbed interface firmware (which uses RTX), not the mbed libraries, so things like the SDFileSystem or MSCFileSystem will not necessarily have the same limitation. Although I haven't confirmed this, but worth a try if that gives you what you want.

Simon

14 Nov 2010

Maybe "w+b" would work then?

15 Nov 2010

Sorry I forgot to mention that neither "wb" nor "w+b" works. I should have changed the sample code, as I already read about the fseek - textmode problems.I even tried flushes between calls but the result is the same.

15 Nov 2010

@Simon: If it is the case that fseek is not supported for "w" mode (I assume this includes "wb" mode"), then I'll have to check other ways. However the information that the underlying system is the Keil RTX may help me to find more information.

Thanks

15 Nov 2010

Simon,

I tried it with the MSCFileSystem and it works as expected. Thanks for the hint.

Andreas