while (fscanf(inFile, "%[^ \n] ", string) != EOF) has huge problems.
The format string "%[^ \n] " is made up of 2 directives: "%[^ \n]" and " ".
"%[^ \n]" is a format specifier made up of a scanset. The scanset consists of all char except ' ' and '\n'. So fscanf() looks for 1 or more characters that are in the scanset and saves them to string.
"%[^ \n]" has 2 problems:
1) If the first character encountered is not in the scanset, fscanf() ungets that character back to inFile and the function returns 0. No further scanning occurs. So if inFile begins with a ' ', code puts nothing in string, inFile is not advanced and subsequent code is set up for UB or an infinite loop!
2) The numbers of characters to save in string is unbounded. So if inFile begins with more that the sizeof(string)-1 char in the scanset, undefined behavior ensues.
" " directive tells fscanf() to consume 0 or more white-space char. This can be confusing should inFile have the value stdin. In that case, the user needs to enter some non-white-space after the ' ' or '\n'. Since stdin is usually line buffered, that means something like "abc\ndef\n" needs to be entered before scanf() saves "abc" and returns 1. The "def\n" is still in stdin.
Recommend instead:
char string[100];
while (fscanf(inFile, "%99s", string) == 1) {
...
}
"%99s" will consume optionally leading white-space, then up to 99 non-white-space char, appending the usual \0.
fscanfto read strings (or character sequences) is quite dangerous and should be avoided. Ifchar string[buffer_size]is not large enough to hold the contents, it will overflow and could compromise your system. One could use the POSIX.1-2008mmodifier but it's not very portable.%254s. It is not dangerous if you use it correctly.fscanfto read strings of unknown length is dangerous. If you specify a field width like%255[^ \n]then it's safer, but could still lead to unexpected behaviour and it gets cumbersome to handle the question "didstrlen(string) == 255because the word was exactly that long, or will my next read string be a continuation of the previous one, and how can I know?"%n, one can say:if (items_read > 0 && strlen(string)) > n. It will be true if whitespace was consumed, as in:%nwill hold the number of characters read including white space.