Syntax:
Example
int fprintf(FILE *stream, const char *format [, argument, ...])
Example
Example
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading File : fscanf function
The fscanf function is employed to retrieve a series of characters from a file. It extracts a word from the file and signals the end of the file by returning EOF.
Syntax:
Example
int fscanf(FILE *stream, const char *format [, argument, ...])
Example
Example
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
Output
Hello file by fprintf...
C File Example: Storing employee information
Let's explore an illustration of file manipulation to save employee details inputted by the user from the terminal. We will be storing the employee's identification, name, and earnings.
Example
Example
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
Output:
Output
Enter the id
1
Enter the name
sonoo
Enter the salary
120000
Now, access the file in the present working directory. If you are using a Windows operating system, navigate to the TC\bin directory where you will find the emp.txt file containing the details below.
emp.txt
Example
Id= 1
Name= sonoo
Salary= 120000