r/cprogramming • u/Straight_Oil8775 • Feb 28 '26
Which approach is better?
So I'm relatively new to C, coming from java. and I'm semi used to MMM now but I'm writing a program that reads files that can sometimes be really large (over 1gb (most likely smaller though)) would it be better to load the file into memory and add a pointer to the first character in memory or use a char array dynamically allocated based off of the file size?
9
Upvotes
12
u/EpochVanquisher Feb 28 '26
What is the difference, here?
Usually “load into memory” leaves you with a char array in memory, after you’re done loading.
(You can alternatively use mmap, if you want. But it’s more complicated and less portable.)
2
u/wsbt4rd Feb 28 '26
You really want to use mmap
mmap(2) - Linux manual page https://share.google/hWP73hpXs2yirZ4xW
It's been the right way to do this, since the early days of POSIX.
1
u/Eidolon_2003 Feb 28 '26
Are you targeting a specific operating system, or are you sticking to the standard library?
1
u/Paul_Pedant Feb 28 '26
Please first explain why you have to read the entire file into memory all at once ?
You can usually quite happily process a 1TB file a line at a time (stdio will optimise using a block at a time, but that's probably not your concern).
If you really need random access to parts of the data, you can seek around a file quite easily.
1
u/Plane_Dust2555 Feb 28 '26
Two things here:
1- Don't allocate space for the entire file. Even when, in architectures like x86-64, where you have enough memory and the environment can accommodate such amount of dynamic memory allocation, to deal with such a block can be slow and "painful";
2- Build your code to deal with chucks of the file (let's say a 32 KiB chuck)... This way you can use your buffer dynamically allocated or statically allocated (arrays) - the former can be allocated in the stack with no problems...
Ahhh... I have a question: What MMM means?
1
u/PantsOnHead88 Feb 28 '26
Loading the whole file into memory may work great for small files while learning, but it’s not scalable beyond a certain point. If you learn to handle things in blocks and assemble indexes, you can work with TB-sized files as easily as smaller ones. Not only does it scale up to potential monster file sizes, but it also scales down to resource limited systems.