Alex Rivera | Logout

reading a text file into an array in c

Asked 2009-01-04T12:57:01.387
18

What would be the most efficient method of reading a text file into a dynamic one-dimensional array? reallocing after every read char seems silly, reallocing after every read line doesn't seem much better. I would like to read the entire file into the array. How would you do it?

Edit
Report

1 Answer

12

If mmap(2) is available on your system, you can open the file and map it into memory. That way, you have no memory to allocate, you even don't have to read the file, the system will do it. You can use the fseek() trick litb gave to get the size.

void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset);

EDIT: You have to use lseek() to obtain the size of the file, .

int fd = open("filename", O_RDONLY);
int nbytes = lseek(fd, 0, SEEK_END);
void *content = mmap(NULL, nbytes, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
answered 2009-01-04T14:21:55.240

Your Answer