I have been trying to create a c program to print the current content of a .txt file, allow the user the enter what content they wish to be there instead, and then print that content over the previous txt file. However the resulting .txt file has ')'
printed, replacing characters where is is printed.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fileDisplay = fopen("password1.txt", "r" );
char c;
printf("Current Password is: ");
do{
c = fgetc(fileDisplay);
printf("%c", c);
}
while (c != EOF);
fclose(fileDisplay);
char np[]="";
printf("\nPlease Enter New Password: \n");
scanf(" %s", np);
FILE *file = fopen("password1.txt", "w" );
fprintf(file," %s", np);
fclose(file);
return 0;
}
For example, if the user inputs
Password
as the char np
, the output from the fprintf
is
P')'uord
The array
np
only has room for one character (the terminating'\0'
of the empty string""
that you initialize it with), since you do not specify a size for it. Thus it can not fit any string other than the empty string and the rest of the user's input overflows, causing undefined behaviour.You need to provide an array large enough to hold the user's input (specify a size between the
[]
) and you should also inform the input function (currentlyscanf
, butfgets
might be better here) of this size so that it knows not to write past the end of your array.edit: As pointed out by @LuisColorado, another problem is that
char c
cannot hold all possible return values offgetc
:EOF
is not achar
(otherwise it would be impossible to distinguish the end of file from theEOF
character in the file itself). Useint c
instead ofchar c
, and check forEOF
before printing it (since you don't want to print theEOF
), e.g.: