Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the size of a file created by fmemopen

Tags:

c

linux

stdio

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

like image 417
Tal Darom Avatar asked Oct 14 '25 10:10

Tal Darom


2 Answers

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.

like image 77
UmNyobe Avatar answered Oct 16 '25 22:10

UmNyobe


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.

like image 21
Tal Darom Avatar answered Oct 16 '25 23:10

Tal Darom