In C, we can create a file and store user input data inside it using file handling functions. In this program, the file is opened using fopen() in "w+" mode, which allows writing data into the file. The scanf() function is used to accept values from the user, and fprintf() writes those values into the file.
How It Works?
FILE *fp.fopen() in "w+" mode.scanf().fprintf().fclose().#include <stdio.h> #include <conio.h> main() { FILE *fp; int id, salary; char name[100]; clrscr(); fp = fopen("xyz.txt", "w+"); if(fp == NULL) { printf("File does Not Exist"); return; } printf("\n Enter the ID. : "); scanf("%d", &id); fprintf(fp, "\n id=%d", id); printf("\n Enter the Name : "); scanf("%s", name); fprintf(fp, "\n Name=%s", name); printf("\n Enter the Salary : "); scanf("%d", &salary); fprintf(fp, "\n Salary=%d", salary); fclose(fp); getch(); }
xyz.txt File Content:
scanf(). Accept the following information from the user:
fprintf().fopen("employee.txt","w+"). Use scanf() to accept values and write them into the file using fprintf(). Finally, close the file using fclose().
#include <stdio.h> #include <conio.h> main() { FILE *fp; int id, salary; char name[50]; clrscr(); fp = fopen("employee.txt", "w+"); printf("\n Enter Employee ID : "); scanf("%d", &id); fprintf(fp, "\n ID = %d", id); printf("\n Enter Employee Name : "); scanf("%s", name); fprintf(fp, "\n Name = %s", name); printf("\n Enter Employee Salary : "); scanf("%d", &salary); fprintf(fp, "\n Salary = %d", salary); fclose(fp); getch(); }
employee.txt File Content:
employee.txt using fopen(). It accepts employee details from the user using scanf() and stores the information in the file using fprintf(). The file is closed using fclose() after saving the data.