C fprintf() and fscanf()
Please find below explanation about C fprintf() and fscanf() with examples –
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...
Related Post:
Features of C Programming Language
Dynamic memory allocation in C
Difference Between Type Casting and Type Conversion in C
Difference Between Variables and Constants
C Program to generate Fibonacci Triangle
C Program to print “hello” without semicolon
C Program to swap two numbers without third variable
Count the number of digits in C