0

In Linux(ubuntu) fpos_t is in a struct

typedef fpos_t {
    size_t _pos,
    size_t _state
}

In Windows, fpos_t is not defined. In the code base, it is defined in this way.

#ifndef _FPOS_T_DEFINED
typedef __int64 fpos_t;
#define _FPOS_T_DEFINED
#endif  /* _FPOS_T_DEFINED */

However, in my code

foo () {
    fpos_t fsize;
    fgetpos(fp, &fsize);    // Function A

    bar.len = (unsigned int)fsize;                      // for windows  Function B      
    bar.body = (char *)SAFE_MALLOC( (size_t)fsize);     // for windows
    //bar.len = (unsigned int)fsize._pos;                   // for linux Function B
    //bar.body = (char *)SAFE_MALLOC( (size_t)fsize._pos);// for linux
}

Question is what is the elegant way to substitute the fsize._pos to fsize when compiled in different platform. Method I knew

#if defined(LINUX)
    //code for linux
#else 
    //code for windows
#endif 
zero
  • 193
  • 1
  • 11

1 Answers1

4

The fpos_t structure is defined to be opaque; there is no portable way to extract a file offset from an fpos_t (Cast fpos_t to int or char).

If you want to get the byte offset of a file position, open the file in binary mode and use ftello (ftello/fseeko vs fgetpos/fsetpos).

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • To generalize this question, not particularly for fpos_t. How should I handle this situation that in different system a variable is defined in two different types. However, some API calls won't effect by this changes, but some do. Like this case, function A doesn't have issue, but function B has. – zero Jan 28 '16 at 19:49
  • 1
    @zero in general, you can abstract the non-portable operation into a (possibly inline) function, and place the platform-specific code in the definition of that function, using `#ifdef` etc. – ecatmur Jan 28 '16 at 19:55
  • Thanks, That's what I thought. Maybe this is the best way to do this. – zero Feb 01 '16 at 15:23