fprintf outputting ')' in txt file

122 Views Asked by At

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

3

There are 3 best solutions below

2
On BEST ANSWER

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 (currently scanf, but fgets 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 of fgetc: EOF is not a char (otherwise it would be impossible to distinguish the end of file from the EOF character in the file itself). Use int c instead of char c, and check for EOF before printing it (since you don't want to print the EOF), e.g.:

while ((c = fgetc(fileDisplay)) != EOF) {
    putchar(c);
}
0
On

There is no enough memory in np to store the user entered string(Password).

Change

char np[]=""; /* Here np can atmost hold only 1 character, which now is '\0' */

to

char np[10]=""; /* here 10 is arbitrary, change to the max value of the string length that can be expected from the user */
0
On
char np[] = "";

is equivalent to:

char np[1] = {'\0'};

which creates a char array of 1 elment, not enough to store any string other than an empty string.