Read the file in dynamic memory array using malloc and POSIX file operations.

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

I am trying to read a file in a dynamic array. Firstly, I open the file using open (), so I get the file descriptor But then I do not know how I can allocate memory using malloc for a dynamic array to make some changes to the data in the file from memory.

+4
source share
3 answers

Please search for SO before posting questions, I think you can find your answer here:

reading a text file into an array in c

+3
source

open (), lseek () at the end of the file, getting the file size using the tell () command, and then allocating memory accordingly will work as suggested above.

If there is no particular reason for this, fopen (), fseek (), ftell () is a better idea (portable within the standard C library).

This, of course, assumes that the file you are opening is small. If you work with large files, allocating memory for the entire file might not be a good idea.

You may like to use memory mapped files for large files. POSIX systems provide the mmap () and munmap () functions for matching files or devices in memory. See mmap man for more details. Files with memory mapping work similarly to C arrays, although the responsibility for obtaining the actual file data is provided by the OS, which extracts the corresponding pages from the disk as necessary when working on the file.

The memory card mapping approach has limitations if the file size is larger than the 32-bit address space. Then you can display only part of the file at a time (on 32-bit machines).

+2
source

like this:

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

bytes are now in the buffer

-one
source

All Articles