Reputation: 105
I am trying to read thousands of words and print only the first 15 but the only word that it prints is the very last one in the array where I stored the words.
g++ --version g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
From the following answer I derived the code below to read a file line by line C read file line by line
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
unsigned char *words[25143];
int readDictionary(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
int count = 0;
fp = fopen("dictionary.txt", "r");
if (fp == NULL)
{
printf("failed to open file");
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1) {
printf("%s", line);
words[count] =(unsigned char*) line;
count++;
}
fclose(fp);
if (line)
free(line);
}
int main (void)
{
readDictionary();
printf("we just read the dictionary\n");
for (int k= 0; k <15; k++)
{
printf("%d %s",k,(unsigned char*)words[k]);
}
}
Upvotes: 1
Views: 1058
Reputation: 147
to print a whole array/vector you need to iterate through all the items. example: you have a vector of 5 units, to print all of it you need to
//Pseudo code
for(int i = 0;i < vectorex;i++)
{
print vectorex[i];
}
this way it will iterate throught all anwser's and print it all
Upvotes: 0
Reputation: 61
All pointers in your array are getting set to the same char * (line) which is getting overwritten every iteration in the loop leaving you with an array of char pointers that has the same pointer in each index of the array and that pointer points to a location in memory that has been written over and over until you overwrite it with the last item in the dictionary. To do this the way you are wanting to line would need to use a different char * for each iteration in your loop.
Upvotes: 1
Reputation: 3873
Take a look at description of getline, which tells that it'll only allocate buffer if line passed is NULL. It'll only be NULL the first time and consequently will reuse the buffer or increase it if line doesn't fit.
If you want it to allocate separate buffers for every word, do
printf("%s", line);
words[count] =(unsigned char*) line;
line = NULL;
count++;
and remove the
if (line)
free(line);
but don't forget to free all non-NULL entries of words somewhere later on.
Upvotes: 2