I have a question related to strings and pointers.
Please explain only with C/C++ programs….
There is a file, which contains 1 word in each line.
I knew the no. of words that are there in the file. Please explain with the help of small code, how I can store those words in RAM, efficiently.
Is fscanf(fp,"%s",word) & strcpy , the only way to store the words in RAM… no other efficient algo or logic available..
Thanks.
Probably the most efficient way to do this is to read the whole file into memory in one block (use
fread). Then allocate an array of pointers, one for each word. Then walk through the file in memory, changing the\ncharacters to\0and storing a pointer the the character after each\0in your array.It is efficient because it only performs one I/O operation, two memory allocations, and loops over the characters in the file twice (once to copy them to the buffer, and once again to break them up into separate strings). The algorithm you describe (
fscanfandstrcpy) will perform many I/O operations, allocate memory for each word, and loops over the characters at least three times (once to read into the buffer, once to find the length to allocate memory for, and once to copy from the buffer into the allocated memory).Here’s a simple version with no error checking:
Here’s a slightly simpler version using
strtok:Note that the above two examples assume that the last word in the file ends with a newline!