Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load file content into memory, C

Tags:

c

file-io

fopen

I will be dealing with really huge files, for which I want just partially to load the content into memory. So I was wondering if the command:

 FILE* file=fopen("my/link/file.txt", "r");  

loads the whole file content into memory or it is just a pointer to the content? After I open the file I use fgets() to read the file line by line. And what about fwrite()? Do I need to open and close the file every time I write something so It doesn't overloads or it is managed in the background?

Another thing, is there maybe a nice bash command like "-time" which could tell me the maximal peak memory of my executed program ? I am using OSx.

like image 227
malajedala Avatar asked Jan 29 '26 22:01

malajedala


1 Answers

As per the man page for fopen(),

The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it.

So, no, it does not load the content of the file into memory or elsewhere.

To operate on the returned file pointer, as you already know, you need to use fgets() and family.

Also, once you open the file, get a pointer and does not fclose() the same, you can use the pointer any number of time to write into the file (remember to open the file in append more). You don't need to open and close for every read and write made to the pointer.

Also, FWIW, if you want to move the file pointer back and forth, you may feel fseek() can come handy.

like image 138
Sourav Ghosh Avatar answered Jan 31 '26 10:01

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!