Introduction
In this lab, you will learn how to create a new file in C programming language and write data to it. The FILE data type is used to represent a file in C, and the fopen() function is used to open a file for reading, writing, or appending. Once a file is opened, data can be written to it using the fprintf() function, and the fclose() function is used to close the file after writing data.
Create a new C program using the terminal
Open the terminal and create a new C program called main.c in the ~/project/ directory using the command:
nano ~/project/main.c
Include necessary header files
In the main.c file, include the necessary header files:
#include <stdio.h>
#include <stdlib.h>
Define variables and pointers
Define variables and pointer of type FILE to hold the file and its content:
FILE *fptr;
char name[20];
int age;
float salary;
Open a file for writing
Open a file for writing using the fopen() function. If the file does not exist, it will be created. Otherwise, its contents will be overwritten:
fptr = fopen("emp.txt", "w");
if (fptr == NULL)
{
printf("File does not exist.\n");
return 1;
}
Write data to the file
Ask the user to enter the employee's name, age, and salary, and write it to the file using the fprintf() function:
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);
Close the file
Close the file using the fclose() function:
fclose(fptr);
Complete the code
#include <stdio.h>
#include <stdlib.h>
int 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 exist.\n");
return 1;
}
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);
return 0;
}
Summary
In this lab, you have learned how to create a new file in C programming language and write data to it using the FILE, fopen(), fprintf(), and fclose() functions. Remember to always close the file after writing data to it to avoid data loss.



