Sahat Yalkabov
Sahat Yalkabov

Reputation: 33624

Reading file into char array in C: Or how to dynamically allocate an array?

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

Answers (4)

sigjuice
sigjuice

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

Mike
Mike

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

paulsm4
paulsm4

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

cnicutar
cnicutar

Reputation: 182619

Well, if you're on linux you can use stat(2) to get the file size. The structure stat contains a field st_size which indicates the total size in bytes.


Is reading the entire file in memory really the best way to go ?

Upvotes: 2

Related Questions