Create File With Scanf


Explanation

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?

  • Step 1: Declare a file pointer using FILE *fp.
  • Step 2: Declare variables to store ID, name, and salary.
  • Step 3: Create and open the file using fopen() in "w+" mode.
  • Step 4: Check whether the file is successfully opened or not.
  • Step 5: Take employee details from the user using scanf().
  • Step 6: Write the entered details into the file using fprintf().
  • Step 7: Close the file using fclose().

Example Program


#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();

}

Output

Enter the ID. : 101
Enter the Name : Rahul
Enter the Salary : 25000


xyz.txt File Content:

id=101
Name=Rahul
Salary=25000

Practice Exercises

Task 1: Write a C program to create a file named employee.txt and store employee details using scanf(). Accept the following information from the user:
  • Employee ID
  • Employee Name
  • Employee Salary
Goal: Learn how to take user input and store the entered data into a file using fprintf().

💡 Hint: Open the file using fopen("employee.txt","w+"). Use scanf() to accept values and write them into the file using fprintf(). Finally, close the file using fclose().
💡 Show Solution

#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();

}

Output
Enter Employee ID : 101
Enter Employee Name : Amit
Enter Employee Salary : 30000


employee.txt File Content:

ID = 101
Name = Amit
Salary = 30000
Explanation: The program creates a new file named 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.