I am trying to reallocate disk space for file operations, however, I am faced with one strange problem: posix_fallocate only adds one byte when I call it to allocate disk space for files opened using add mode, and the file contents are also unexpected. Did anyone know this problem? And my test codes:
#include <cstdio> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <cerrno> int main(int argc, char **argv) { FILE *fp = fopen("append.txt", "w"); for (int i = 0; i < 5; ++i) fprintf(fp, "## Test loop %d\n", i); fclose(fp); sleep(1); int fid = open("append.txt", O_WRONLY | O_APPEND); struct stat status; fstat(fid, &status); printf("INFO: sizeof 'append.txt' is %ld Bytes.\n", status.st_size); int ret = posix_fallocate(fid, (off_t)status.st_size, 1024); if (ret) { switch (ret) { case EBADF: fprintf(stderr, "ERROR: %d is not a valid file descriptor, or is not opened for writing.\n", fid); break; case EFBIG: fprintf(stderr, "ERROR: exceed the maximum file size.\n"); break; case ENOSPC: fprintf(stderr, "ERROR: There is not enough space left on the device\n"); break; default: break; } } fstat(fid, &status); printf("INFO: sizeof 'append.txt' is %ld Bytes.\n", status.st_size); char *hello = "hello world\n"; write(fid, hello, 12); close(fid); return 0; }
And the expected result should be,
#
However, the result of the above program:
So what is "^ @"?
And the message shows
INFO: sizeof 'append.txt' is 75 Bytes. INFO: sizeof 'append.txt' is 76 Bytes.
Any clues?
thanks
source share