Archived

This topic is now archived and is closed to further replies.

Storing Text From File

This topic is 5901 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''ve have a little problem saving text from a file to a pointer. If I have a variable: char *text; and a file with a bunch of characters that I load in the program, example: abcdefg I want to save the text in the file in the text pointer. Is that possible? I rather not save it on a vector because the length may variate. Could anyone please help me with a solution?

Share this post


Link to post
Share on other sites
Since you must allocate memory anyway, if you don''t know the size of your text, you''re in trouble. Even fscanf needs to write to allocated memory.

One solution is to use a C++ std::string.

Another is to create a linked list, with each node holding a chunk of the file ( say, 4K ), and adding new nodes as you read the file.

A third one is to realloc() the chunk of memory you initially allocated for your text if you discover you need more space.

A fourth is to open your file a first time in binary mode, call fseek() with SEEK_END as a parameter to send the file pointer to the end of the file, then use ftell() to know how far in the file the file pointer is, i.e. how long the file is. Of course, you may get problems here if you have multibyte (Unicode or whatever) characters.

Or...

Share this post


Link to post
Share on other sites