Reputation: 33624
Using Linux system calls open and read. The read call accepts 3 parameters
read(File descriptor, Buffer array, Size of the buffer array);
My question is related to the argument #3. Suppose I have multiple text files that I want to read into my buffer array. But as far as I know C doesn't have something like Vector or ArrayList or any other structure with a dynamic size.
Is there an easy way to calculate the size of the file so I know how much space should I allocate for my char array?
Upvotes: 1
Views: 1602
Reputation: 29749
You could also stat()
the file to determine its size and then call mmap() on it. Your file will appear as an "array" without the need to malloc()
memory.
Upvotes: 7
Reputation: 49363
I don't know if it qualifies as efficient, but it is "easy" to simply move to the end of the file and grab the length from there:
fseek(readf, 0, SEEK_END);
fileLen=ftell(readf);
buffer=(char *)malloc(fileLen);
Upvotes: 2
Reputation: 121599
The usual practice is to read into a fixed length buffer, then copy each "record" into a dynamically allocated structure (e.g. malloc() a struct* or a char*).
As cnicutar suggested, you can also "stat" the file, malloc() a buffer that size, and read the file all at once.
Upvotes: 1