Showing posts with label C fprintf() and fscanf(). Show all posts
Showing posts with label C fprintf() and fscanf(). Show all posts

Sunday, July 8, 2018

C fprintf() and fscanf()

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.

Syntax:





int fprintf(FILE *stream, const char *format [, argument, ...])



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 used to read set of characters from 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, ...])



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:

Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.





#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:

Enter the id

131

Enter the name

Rama

Enter the salary

150000

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 131

Name= Rama

Salary= 150000

EXAMPLE PROGRAM FOR FSCANF(), FPRINTF(), FTELL(), REWIND() FUNCTIONS IN C PROGRAMMING LANGUAGE:

This file handling C program illustrates how to read and write formatted data from/to a file.





#include <stdio.h>

int main ()
{
char name [20];
int age, length;
FILE *fp;
fp = fopen ("test.txt","w");
fprintf (fp, "%s %d", “cprogramming”, 31);
length = ftell(fp); // Cursor position is now at the end of file
/* You can use fseek(fp, 0, SEEK_END); also to move the
cursor to the end of the file */
rewind (fp); // It will move cursor position to the beginning of the file
fscanf (fp, "%d", &age);
fscanf (fp, "%s", name);
fclose (fp);
printf ("Name: %s \n Age: %d \n",name,age);
printf ("Total number of characters in file is %d", length);
return 0;
}



OUTPUT:

Name: cprogramming

Age: 31

Total number of characters in file is 15




Instagram