-1

When I used fputs() to directly store a character array in a file, it stored this in the file:

ÈLwìþ( 

Why was that?

#include <stdio.h>

int main()
{
    FILE *p;
    p=fopen("pa.txt","w+");
    char name[100];
    printf("Enter a string :");
    fputs(name,p);
    fclose(p);
    getchar();
    return 0;
}

When I take input in name using scanf() or gets(), the correct text is stored but when directly use fputs() is used it stored in an unusual format. Why does this happen?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ameyCU
  • 16,489
  • 2
  • 26
  • 41

3 Answers3

2

When I take input in name using scanf() or gets() correct text is stored but when directly fputs() is used it stored in unusual format. Why this happens ?

Accessing uninitialized variable p is undefined behaviour as its value indeterminate as per C standard. There's no explanation for why it happens. Just don't do that.

6.7.9 Initialization, (C11 draft)

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

And indeterminate is defined as:

3.19.2 indeterminate
value either an unspecified value or a trap representation

Note that function gets() has been removed from the recent C standard (C11) and it has never been a safe anyway due to its buffer overflow issues.

P.P
  • 117,907
  • 20
  • 175
  • 238
1

When I take input in name using scanf() or gets() correct text is stored but when directly fputs() is used it stored in unusual format. Why this happens ?

You haven't read the data from stdin before writing it out using fputs.

Use:

fgets(name, sizeof(name), stdin);

and then:

fputs(name, p);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • I also don't understand when I compile and run this code it asks for input and takes input when I don't use scanf() or gets() . – ameyCU Jun 11 '15 at 04:52
  • 1
    @ameyCU, the input is processed by `getchar()`, which reads just one character. The rest are discarded since the program terminates after that. – R Sahu Jun 11 '15 at 05:20
0

You have opened char array but you haven't used it. Analyze the code you will understand.

#include <stdio.h>
int main()
{
    char name[100];

    FILE *p;

    p=fopen("pa.txt","w+");

    if(!p) {
        perror("Error writing");
        return -1;
    }

    printf("Enter a string :");
    scanf("%s",name);
    fputs(name,p);

    fclose(p);

    return 0;
}