I would like to open a file and set its size so that I can then use mmap to write to it.
I found that I can use function truncate
or ftruncate
. Unfortunately, when I include <unistd.h>
I got error:
error: implicit declaration of function ‘truncate’
I read on Internet that I should use gnu or something like that but this is for school project and we have to compile with -std=c99
.
Are there any alternatives?
When you use -std=c99
the C library makes sure that the headers do not declare any symbols that are not reserved/are not defined in the C standard library. Since ftruncate
does not belong to the C standard library, being a POSIX extension instead, it is not defined by default.
A POSIX program must, for maximal compatibility, define the _POSIX_C_SOURCE
feature test macro, or _XOPEN_SOURCE
, with appropriate values, before including the headers.
The feature test macros are listed conveniently on for example Linux manual pages; for ftruncate
these would be:
ftruncate():
_XOPEN_SOURCE >= 500
|| /* Since glibc 2.3.5: */ _POSIX_C_SOURCE >= 200112L
|| /* Glibc versions <= 2.19: */ _BSD_SOURCE
i.e. use
#define _XOPEN_SOURCE 500 // (or greater; current is 700)
#include <unistd.h>
or
#define _POSIX_C_SOURCE 200112L // (or greater)
#include <unistd.h>