gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

DS development > fseek not seeking to end of the file

#138235 - masscat - Tue Aug 21, 2007 4:26 pm

There appears to be a problem with fseeking to the end of a file using libfat/DKA r20.
I have put together some test code to show the problem (see below). The test code writes out "test" followed by "aaaa". It then seeks backwards 5 bytes and writes "a". It then seeks using the supplied offset and whence (SEEK_END etc.) and writes "bbbb".

Calling:
seek_test( "end_test", 0, SEEK_END)
seek_test( "cur_test", 4, SEEK_CUR)
seek_test( "set_test", 8, SEEK_SET)

Should all seek the end of the file and produce the file contents "tesaaaaabbbb" but none of them do. They produce "tesabbbb" followed by four zero or rubbish byte values.

Note, calling:
seek_test( "end_test", -1, SEEK_END)
seek_test( "cur_test", 3, SEEK_CUR)
seek_test( "set_test", 7, SEEK_SET)

All produce "tesaaaabbbb" as they should, so it is only the end of file case that seem to be a problem.

Here is the test code:
Code:
int
seek_test( const char *filename, long offset, int whence) {
  int test_good = 1;
  u8 temp_write[4] = {"test"};
  FILE *test_file = fopen( filename, "wb+");

  if ( test_file != NULL) {
    if ( fwrite( &temp_write, 1, 4, test_file) == 4) {

      int j;
      for ( j = 0; j < 4; j++)
        temp_write[j] = 'a';

      if ( fwrite( &temp_write, 1, 4, test_file) == 4) {
        /*
         * seek back a bit and write something then seek to the
         * end again.
         */
        if ( fseek( test_file, -5, SEEK_CUR) == 0) {
          if ( fwrite( &temp_write, 1, 1, test_file) == 1) {

            /*
             * THE SEEK TO END
             */
            if ( fseek( test_file, offset, whence) == 0) {
              for ( j = 0; j < 4; j++)
                temp_write[j] = 'b';

              if ( fwrite( &temp_write, 1, 4, test_file) != 4) {
                test_good = 0;
              }
            }
            else
              test_good = 0;
          }
          else
            test_good = 0;
        }
        else
          test_good = 0;
      }
      else
        test_good = 0;
    }
    else
      test_good = 0;

    fclose( test_file);
  }
  else {
    iprintf("Failed to open file\n");
  }

  return test_good;
}