user9062823
user9062823

Reputation:

Reading file word by word

I don't know why but my code prints a list of (null)(null)(null).... I have to print the list of words from a file 'words.txt'. Another question is: fscanf ignore white spaces?

#define WORD_LENGTH 1024
#define SIZE_QUOTE 100

int main(){
  char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
  long i;
  for(i = 0; i < SIZE_QUOTE; i++){
    if(!(malloc(sizeof(char) * (size_t)WORD_LENGTH)))
      exit(1);
  }
  i = 0;
  FILE *pf = fopen("words.txt", "r");
  while(!feof(pf) && i < SIZE_QUOTE){
    fscanf(pf, "%s", quote[i]);
    printf("%s", quote[i]);
    i++;
  }
  fclose(pf);
  free(quote);
}

Upvotes: 0

Views: 79

Answers (1)

jmc
jmc

Reputation: 538

You're never assigning the return value of malloc() to quote[i] so they end up staying NULL (if you're lucky):

  char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
  long i;
  for(i = 0; i < SIZE_QUOTE; i++){
    if(!(malloc(sizeof(char) * WORD_LENGTH)))

It should be something like this instead:

  char **quote = malloc(sizeof(char*) * (size_t)SIZE_QUOTE);
  for(int i = 0; i < SIZE_QUOTE; i++){
    quote[i] = malloc(sizeof(char) * WORD_LENGTH);
    if(!quote[i])

Also you could avoid malloc() entirely and statically initialize that array if all the sizes are known:

char quote[SIZE_QUOTE][WORD_LENGTH] = {{'\0'}};

Also, you should be free()-ing the individual quote[i] at the end too:

for(int i = 0; i < SIZE_QUOTE; ++i) free(quote[i]);
free(quote);

There's other mistakes that have been pointed out through the comments already, so I won't elaborate further.

Upvotes: 1

Related Questions