Thursday 1 June 2017

Create and Write in File in C ~ GNIITHELP

Program to Create a File & Write Data in it

In this program we will be creating a new file and will then store information in it.
#include<stdio.h>
#include<conio.h>

void main()
{
    FILE *fptr;
    char name[20];
    int age;
    float salary;
 
    /*  open for writing */
    fptr = fopen("emp.txt", "w");
 
    if (fptr == NULL)
    {
        printf("File does not exists \n");
        return;
    }
    printf("Enter the name \n");
    scanf("%s", name);
    fprintf(fptr, "Name  = %s\n", name);
    
    printf("Enter the age\n");
    scanf("%d", &age);
    fprintf(fptr, "Age  = %d\n", age);
    
    printf("Enter the salary\n");
    scanf("%f", &salary);
    fprintf(fptr, "Salary  = %.2f\n", salary);
    
    fclose(fptr);
}
You can add any information in the file, like we have added Name, Age and Salary for some employees, you can change the program as per your requirements.

No comments:

Post a Comment