Dat Boi Dat Boi - 1 year ago 83
C Question

Writing to a file in C not working

I have the following code, and I keep on getting the "Program has stopped working" error after I have input the characters.

I have done some debugging and found that the issue is in the writing to the file part, however I cannot find the issue.

Can anyone help me? (I'm new to C)

#include <stdio.h>

int main()

char characters;

printf("Input your characters: ");
scanf("%s", &characters);

FILE *fp = fopen("File.txt", "w");
fprintf(fp, "%s", characters);


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download