Home » questions » How can I read an entire text file to a buffer?

How can I read an entire text file to a buffer?

2006-08-14 15:29:36, Category: Programming & Design
Using Win32 functions CreateFile and ReadFile. I don't want to specify a static size for the char [ ] buffer as it will depend on the size of the file. I need a buffer I can pour the entire file into. If somebody can point me to a sample, then that would help. Cheers

Answers

  1. Titus W

    On 2006-08-14 16:06:24


    Wow, it has been forever since I've fooled with Win32. However, being a C and Java programmer, I have run into the same problem and offer this technique in pseudo code. There should be some function to get the "sizeof" the file. With the size, allocate the buffer size, then read the data into the buffer. You should be able to embed the whole whole thing into one line: putInAllocatedMemory(readFile(allocateMemory(sizeof(filename)))). Or, if you would like to make it more readable, you can break it down into a couple of lines. Your compiler should optimize it. I hope this helps.
  2. timespiral

    On 2006-08-14 16:22:55


    The Perl language excels in text manipulation. PERL (Practical Extraction and Reporting Language). You might want to consider that... $file = "yourfile.txt"; @buffer = ""; open(IN_FILE, "<$file") or die("Error: Could not open $file"); @buffer = ; close (IN_FILE); print @buffer;