Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getting text file contents

Status
Not open for further replies.

gacaccia

Technical User
May 15, 2002
258
US
hi all,

is there a way to dump the contents of a text file into a variable in one step/command, or are the only options to read one line at a time or one character at a time to end of file?

thanks,

glenn
 
>> is there a way to dump the contents of a text file into
>> a variable in one step/command

The closest technique to what you say might be considered reading the entire file contents into a buffer of memory. Another might be to use the Win32 Memory Mapped file IO.


-pete
I just can't seem to get back my IntelliSense
 
but even when reading the entire contents into a variable, the only method i'm aware of is doing it character by character or line by line. so you're confirming then that there is no method for reading the whole file in one command, yes? i know that i can make such a method, but c++ standard libraries don't include one, right?

also, do you know if there is any advantage to reading a file character by character or line by line when the goal is to load the entire file into memory?

thanks,

glenn
 
>> so you're confirming then that there is no method for
>> reading the whole file in one command, yes?

No. There is no single function that allocates the memory based on the file size and reads it into the buffer for you. If that is what you want use a language like VB or Delphi or something.

C/C++ languages contain the power for the developer to determine their own memory usage. This means you have to write the code to manage your own memory allocations and clean it up.

>> the only method i'm aware of is doing it character by character or line by line

That is incorrect. For instance the stl::basic_istream::read() function takes a memory location and the number of bytes to read into that location as parameters. Most file IO mechanisms in C/C++ have a similar function.


-pete
I just can't seem to get back my IntelliSense
 
And, considering this is the C++ Microsoft forum and therefore assuming you're targetting Windows, there's always the ReadFile API, which lets you read an entire file into a buffer quite easily.....


Greetings,
Rick
 
...or CFile...

// Textfile -> CString
CFile file(theFileName, CFile::modeRead);
DWORD len = file.GetLength();
CString s;
file.Read(s.GetBuffer(len), len);
s.ReleaseBuffer();
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top