A file is simply a collection of bytes stored in a storage device like tape, magnetic disc, optical disc, etc. We can use the fopen() function to open or create a new file. Similarly, we use the fclose() function to close the file. Given below is the code of the C program to create files and store information. here we have to create a file and store information about a person in terms of his name, age, and salary.
Different Operations can be performed on a File. Important among them are listed below.
STEP 1: Include the header files to use the built-in functions in the C program.
STEP 2: Declare the variable *ftpr as of type FILE, declare the name as a character, age as an integer, salary as a float.
STEP 3: Open the File using the function fopen() with write permission.
STEP 4: If fpr=null, then the display file does not exist. Otherwise, do step 5.
STEP 5: Read the name from the user and save it into the variable name then write it into the File using the function fprintf.
STEP 6: Read the age from the user and save it into the variable age then write it into the File using function fprintf.
STEP 7: Read the salary from the user and save it into the variable salary then write it into the File using function fprintf.
STEP 8: Close the file using fclose().
To create and write data into a file using the C program, we need to understand the below topics, please refer to these topics.
#include <stdio.h>
void main() {
FILE * fptr;
char name[20];
int age;
float salary;
fptr = fopen("emp.rec", "w"); /*open for writing*/
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);
}
Enter the name Ajay Enter the age 25 Enter the salary 25000 ------------------------------------- Please note that you have to open the file called emp.rec in the directory Name = Ajay Age = 25 Salary = 25000.00