Skip to main content
2 of 2
addl info
DinoCoderSaurus
  • 28.6k
  • 2
  • 12
  • 31

Do not use string word = NULL. fscanf will not "put" anything in it because NULL is a defined constant, and it will not give an error. You could end up in an infinite loop (it also will not detect EOF).

Declaring word as a char array is a fine approach. Remember 45 letters will "fit" in the array declared char word[45], but the "%s" directive of fscanf will try to make it a valid string, and will therefore need one more byte for the null terminator.

Another option would be to use the C type char * and allocate it with malloc or calloc.


In the interest of completeness, there is a "more comfortable" approach. You can use the "m" option in the conversion specification, and fscanf will allocate the memory; it is up to the programmer to free it. Something like this:

string word;
while(fscanf(infile,"%ms",&word) != EOF)
{
    // do "word" logic
    free(word);
}

From man fscanf:

An optional 'm' character. This is used with string conversions (%s, %c, %[), and relieves the caller of the need to allocate a corresponding buffer to hold the input: instead, scanf() allocates a buffer of sufficient size, and assigns the address of this buffer to the corresponding pointer argument, which should be a pointer to a char * variable (this variable does not need to be initialized before the call). The caller should subse‐ quently free(3) this buffer when it is no longer required.

DinoCoderSaurus
  • 28.6k
  • 2
  • 12
  • 31