[Solved] Writing to a file in C not working


In your code, characters is of type char which is not fit to store a string. You need to make characters as an array.

Essentially, what happens behind the hood is, because of %s, the input value (even if a single char) gets stored in the memory pointed by the address supplied, but after that, the attempt to store the terminating null, causes out of bound access. This invokes undefined behavior.

Quoting C11, chapter ยง7.21.6.2, fscanf(), (emphasis mine)

s Matches a sequence of non-white-space characters.286)

If no l length modifier is present, the corresponding argument shall be a
pointer to the initial element of a character array large enough to accept the
sequence and a terminating null character, which will be added automatically.

1

solved Writing to a file in C not working