4

I'm using fmemopen to create a variable FILE* fid to pass it to a function the reads data from an open file.

Somewhere in that function it uses the following code to find out the size of the file:

fseek(fid, 0, SEEK_END);
file_size = ftell(fid);

this works well in case of regular files, but in case of file ids created by fmemopen I always get file_size = 8192

Any ideas why this happens? Is there a method to get the correct file size that works for both regular files and files created with fmemopen?

EDIT: my call to fmemopen:

fid = fmemopen(ptr, memSize, "r");

where memSize != 8192

EDIT2:

I created a minimal example:

#include <cstdlib>
#include <stdio.h>
#include <string.h>
using namespace std;

int main(int argc, char** argv)
{
    const long unsigned int memsize = 1000000;
    void * ptr = malloc(memsize);
    FILE *fid = fmemopen(ptr, memsize, "r");
    fseek(fid, 0, SEEK_END);
    long int file_size = ftell(fid);
    printf("file_size = %ld\n", file_size);
    free(ptr);
    return 0;
}

btw, I am currently working on another computer, and here I get file_size=0

Tal Darom
  • 1,379
  • 1
  • 8
  • 26
  • Can you show the `fmemopen` code that you are using, you will probably find that `ftell` is returning the size of the buffer that you have specified. – Lawrence Woodman Nov 20 '12 at 11:31
  • This shouldn't happen if you have used `fmemopen` as you have described. Try creating the smallest piece of code that demonstrates the problem and post that. – Lawrence Woodman Nov 20 '12 at 11:42

2 Answers2

2

In case of fmemopen , if you open using the option b then SEEK_END measures the size of the memory buffer. The value you see must be the default buffer size.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
  • Thanks! I hope you don't mind me editing the link to point at where this option is stated. BTW, the value 8192 was the offset to the first character in the file that was 0. (see my answer below). – Tal Darom Nov 21 '12 at 08:05
  • adding a link to the man page where this is explained: http://www.kernel.org/doc/man-pages/online/pages/man3/fmemopen.3.html – Tal Darom Nov 21 '12 at 10:37
1

OK, I have got this mystery solved by myself. The documentation says:

If the opentype specifies append mode, then the initial file position is set to the first null character in the buffer

and later:

For a stream open for reading, null characters (zero bytes) in the buffer do not count as "end of file". Read operations indicate end of file only when the file position advances past size bytes.

It seems that fseek(fid, 0, SEEK_END) goes to the first zero byte in the buffer, and not to the end of the buffer.

Still looking for a method that will work on both standard and fmemopen files.

Tal Darom
  • 1,379
  • 1
  • 8
  • 26