Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

What is wong with my code

+1 vote
asked Apr 23, 2021 by Ronald DelPorto (130 points)
I'm a C++ programmer, so get lost on IO and strings in C, so please forgive my ignorance.

This program fails on the fclose statement. It says the file does not exist.  If that is the case, I'd expect it to fail on the open or the fprintf.

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

int main()
{
    FILE *fptr;
    char contact[100], contact1[100];
    printf("Enter first name, last Name, phone number\n");
    gets(contact);
    fopen("ContactList.txt","w");
     fprintf(fptr,"%s  %c",contact, '\n');
   fclose(fptr);
     fopen("ContactList.txt","r");
     fscanf(fptr,"%d", "%s %s %s ",contact1);

    printf("%s %s %s %c",contact1, '\n');
    return 0;
}

2 Answers

0 votes
answered Apr 27, 2021 by Peter Minarik (86,860 points)

There are many problems with your code.

First of all, fopen returns the pointer of the opened file, which you do not store in fptr (which remains to store a random memory address).

Second, scanf and printf argument count did not match the format string.

I've fixed your code below:

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

int main()
{
    char contact[100];
    printf("Enter first name, last Name, phone number\n");
    fgets(contact, sizeof(contact), stdin);
    FILE * fptr = fopen("ContactList.txt", "w");
    if (!fptr)
    {
        printf("Failed to create file.\n");
        return -1;
    }
    
    fprintf(fptr, "%s\n", contact);
    fclose(fptr);

    fptr = fopen("ContactList.txt", "r");
    if (!fptr)
    {
        printf("Failed to open file.\n");
        return -2;
    }
    char firstName[100];
    char lastName[100];
    char phoneNumber[100];
    fscanf(fptr, "%s %s %s", firstName, lastName, phoneNumber);
    printf("First name: %s\n", firstName);
    printf("Last name: %s\n", lastName);
    printf("Phone Number: %s\n", phoneNumber);
    return 0;
}
0 votes
answered Apr 28, 2021 by YASH CHORDIA (160 points)

You have not assigned file location to your pointer *fptr.
Try,

fptr = fopen("ContactList.txt","w");

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...