Storing Text From File
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?
you''d just use
fscanf(fp,"%s",&text);
assuming "fp" is your file variable.
A CRPG in development...
Need help? Well, go FAQ yourself.
fscanf(fp,"%s",&text);
assuming "fp" is your file variable.
A CRPG in development...
Need help? Well, go FAQ yourself.
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...
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...
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement