fprintf():
- A pre-defined function belongs to stdio.h header file.
- A function is used to write set of characters into file.
- This function is used to write stream with specific format.
- printf() function write the data on console where fprintf() do the same thing in file.
- fprintf() function has an additional argument which is a file pointer to the file where the formatted output will be written.
- On success, it returns the total number of characters written to the file. On error, it returns EOF.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, …])
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("tutipy.txt", "w");
fprintf(file, "fprintf() function explained by tutipy...\n");
fclose(file);
return 0;
}
fscanf():
- It is pre-defined in stdio.h
- It is used to read the stream from the file.
- It reads a word from the file and returns EOF at the end of file.
Syntax:
int fscanf(FILE *stream, const char *format [, argument, …])
#include <stdio.h>
int main()
{
FILE *file;
char arr[255];
file = fopen("tutipy.txt", "r");
while(fscanf(file, "%s", arr)!=EOF)
{
printf("%s ", arr);
}
fclose(file);
return 0;
}
Program to Store Employee Data:
#include <stdio.h>
int main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");
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);
return 0;
}