Unable to write in a file after reopening it

Viewed 37

I am writing a program in which the program asks user to enter name, rollno, email in a file. It works fine for the first time but when I try to write more records in the same file it doesn't show those records.

The code is attached below:

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

int main() {
    FILE* fptr;

    char name[20];
    char roll_number[10];
    char email[30];
    printf("Enter your name:");
    scanf("%s", name);

    printf("Enter your roll_number:");
    scanf("%s", roll_number);

    printf("Enter your email:");
    scanf("%s", email);

    fptr = fopen("text.txt", "w");
    fputs("Name:", fptr);
    fputs(name, fptr);
    fputs("\nRoll Number:", fptr);
    fputs(roll_number, fptr);
    fputs("\nEmail:", fptr);
    fputs(email, fptr);
    
/*it works fine till here */
    fclose(fptr);

    printf("Enter your name:");
    scanf("%s", name);

    printf("Enter your roll_number:");
    scanf("%s", roll_number);

    printf("Enter your email:");
    scanf("%s", email);

    fptr = fopen("text.txt", "a");
    fputs("\nName:", fptr);
    fputs(name, fptr);
    fputs("\nRoll Number:", fptr);
    fputs(roll_number, fptr);
    fputs("\nEmail:", fptr);
    fputs(email, fptr);
    
/* the second record doesn't show up */
    return 0;
}
0 Answers
Related