0

After reading numerous report on stackoverflow, I decide to go with FILE* (over std::fstream) to manipulate quickly my binary files. Furthermore, I needed to truncate my file during the process (_chsize or ftruncate), which will work only with a file descriptor (fileno call).

So I am trying to have something like this working (C++):

#define _FILE_OFFSET_BITS 64
#include <stdio.h>
static inline off_t FTello(FILE *stream)
{
#if _WIN32
#if defined(__MINGW32__)
  return ftell( stream ); // 32bits
#else
  return _ftelli64( stream );
#endif
#else
  return ftello( stream );
#endif
}

However this is clearly not working on Visual Studio. I could not find anywhere in the documentation a way to change the size of off_t at compilation time.

It would be tempting to have a signature like this (I assume I have C99: stdint.h):

static inline int64_t FTello(FILE *stream)

What others have been doing ?

For reference, here is what I have been reading, which seems to indicate FILE* provide better performance:

Community
  • 1
  • 1
malat
  • 12,152
  • 13
  • 89
  • 158
  • 1
    What is wrong with using `off_t` in itself? It should be suitable for whatever `FILE *` you are using. – Mats Petersson Jul 25 '13 at 16:39
  • **Why** are you going with `FILE*`? There’s nothing wrong with `std::ofstream`. Performance is not an issue – it’s exactly as fast as `FILE*`. – Konrad Rudolph Jul 25 '13 at 16:42
  • EDIT: You’be been reading bullshit. **`FILE*` is *not* faster than `std::ostream`.** If your file access is really slow and a bottle neck, the only solution is to use memory-mapped files. (And in fact the thread you link to more or less says as much.) There is *one* answer which says the opposite, and it’s by the OP himself. The only person who actually knows what he’s talking about in the other thread is Loki Astari, who did a benchmark and found no difference. – Konrad Rudolph Jul 25 '13 at 16:48
  • @konrad-rudolph Thanks for the clarification about performance. However I still need to call ftruncate() / _chsize in my code. Which only works with an input from fileno(). – malat Jul 25 '13 at 16:53
  • @malat Ah, that changes everything. Ignore me. ;-) – Konrad Rudolph Jul 25 '13 at 16:53

1 Answers1

1

If you are already enforcing large file support, just define FTello() to return int64_t.

You might find inttypes.h more portable than stdint.h though.

MS is not famous for being compatible with UNIX, even though they provide similarly named functions. If you are going to provide a compatibility layer, better look into what existing layers do (e.g. boost.filesystem), there are subtleties everywhere.

By the way, boost.filesystem has resize_file().

DanielKO
  • 4,422
  • 19
  • 29