OldWildWeb Logo

Open, Read and Write large files in C

How to handle large files in C with GCC under Linux

How to open large files in C Linux

Read, open and write large files in C is always a confusing topic due to the lack of documentation and clear examples, I have decided to share a code example of how to handle large files in C with GCC in this article.
To enable the 64 bit file functions we have to define the large file support constant with the following define, #define _LARGEFILE64_SOURCE in the very 1st line of the code, GCC will enable the LFS (large file support) if the constant is defined.
After that the function fopen64 can be used to open files in LFS mode, the function will return a standard FILE pointer as the standard fopen function, after that the standard functions can be used to handle large files in C.

Large file support example GCC:

#define _LARGEFILE64_SOURCE //Must be at the very beginning of the source file
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define BUFFER_SIZE 1024
int main(int argc, char** argv)
FILE *fd = fopen64("newFile.txt", "wb");
fprintf(fd, "This is a string");
fclose (fd);
char dataBuffer[BUFFER_SIZE];
int readen;
FILE *fdRead = fopen64("newFile.txt", "rb");
while ((readen = fread(dataBuffer, sizeof(char), BUFFER_SIZE, fdRead)) > 0)
printf("%s", dataBuffer);
memset(dataBuffer, 0, BUFFER_SIZE);
fclose (fdRead);

This is a string

Handle large files in C with GCC

Ultimi articoli