Search code examples
cfile-handlingcfile

Problem with scanf/gets in C file handling


Whenever I run this code, final scanf function to get 'email' input does not execute and I get 'Updated successfully!' message directly! I tried using gets() instead of scanf and I'm getting the same problem. Can someone please explain the problem to me?

The Image of the Output

#include <stdio.h>
#include <stdlib.h>

typedef struct Directory
{
    char name[20], email[20];
    long int phone;
}Directory;

void add()
{
    Directory d;
    FILE *file;
    file = fopen("phonebook.bin", "ab");
    if(!file)
        printf("Failed to open file!");
    else
    {
        printf("Enter the name: ");
        scanf("%[^\n]", &d.name);
        printf("Enter the Phone Number: ");
        scanf("%ld", &d.phone);
        printf("Enter the e-mail ID: ");
        scanf("%[^\n]", &d.email);
        if(fwrite(&d, sizeof(Directory), 1, file))
            printf("Updated successfully!");
        else
            printf("Something went wrong, Please try again!");
    }
    fclose(file);
}

int main()
{
    add();
}

Solution

  • There are multiple problems in your code.

    1. Correct format for char array is '%s'. I really don't know what is '%[^\n]'.

    2. You get memory corruption for sending the address of the char array in scanf(). The name of the array is actually a const pointer to the start of the array. For example : char a[10]; // a is somewhat equivalent to &a[0]. In your example scanf() needs an address for its second argument and the name of the array already is an address; an address to the first element of the array.

    Your code should look like this:

    void add()
    {
        Directory d;
        FILE* file;
        file = fopen("phonebook.bin", "ab");
        if (!file)
            printf("Failed to open file!");
        else
        {
            printf("Enter the name: ");
            scanf("%s", d.name);                   // ---> notice the %s format and the missing &
            printf("Enter the Phone Number: ");
            scanf("%ld", &d.phone);
            printf("Enter the e-mail ID: ");
            scanf("%s", d.email);                  // ---> same here 
            if (fwrite(&d, sizeof(Directory), 1, file))
                printf("Updated successfully!");
            else
                printf("Something went wrong, Please try again!");
        }
        fclose(file);
    }
    

    By doing &d.email in scanf you will crash or get undefined behavior.

    Please put in some effort in research before posting.