5

Possible Duplicate:
reading a text file into an array in c

I'm trying to read a file into a dynamic array. Firstly I open the file using open() so I get the file descriptor But then I don't know how can I allocate the memory using malloc to a dynamic array in order to do some data modification in the file from memory.

Community
  • 1
  • 1
Peter
  • 985
  • 3
  • 12
  • 14
  • Oops, I marked this duplicate, then realised you had stipulated `open()`. The answer is that you use `fstat()` to get the size for a file descriptor, or `lseek(fd,0,SEEK_END)` returns the resulting offset from the beginning of the file, and hence is equivalent to the ISO C `fseek`/`ftell` combi. – Steve Jessop Nov 14 '09 at 16:46
  • So, my apologies for incorrectly voting to close. I don't think I can undo the vote, but I've edited the title in the hope of preventing others from making the same mistake. – Steve Jessop Nov 14 '09 at 16:52
  • Another possibility is to use `fdopen()` to get a FILE*, and then use the answer in that other question. Not sure I'd recommend it, though, I prefer the POSIX API to the ISO one. – Steve Jessop Nov 14 '09 at 16:55

2 Answers2

2

open(), lseek() to the end of file, getting the size of file using tell(), and then allocating memory accordingly would work well as suggested above.

Unless there is specific reason to do it, fopen(), fseek(), ftell() is a better idea (portable staying within the C standard library).

This certainly assumes that the file you are opening is small. If you are working with large files, allocating memory for the whole of file may not be a good idea at all.

You may like to consider using memory mapped files for large files. POSIX systems provide mmap() and munmap() functions for mapping files or devices in memory. See mmap man page for more description. Memory mapped files work similar to C arrays though the responsibility of getting actual file data is left to the OS which fetches appropriate pages from disk as and when required while working on the file.

Memory mapped files approach has limitations if the file size is bigger than 32-bit address space. Then you can map only part of a file at a time (on 32-bit machines).

Shailesh Kumar
  • 6,457
  • 8
  • 35
  • 60
  • Hi Shailesh, could you please advise how to do it using mmap? Thanks – Peter Nov 15 '09 at 13:19
  • Look up the documentation for mmap - in effect it gives you an array which contains the bytes of the file (and optionally, modifying the array modifies the file on disk). But I think in the case of mmap, you should read it for yourself rather than just take a code snippet, because it has quite a few options according to exactly how you want it to work. – Steve Jessop Nov 15 '09 at 14:57
-1

like this:

char *buffer = (char *)malloc(size);
int actual = read(buffer,size,filehandle);

now the bytes are in the buffer

Jeff
  • 1,969
  • 3
  • 21
  • 35