CodesJava

Easy learning with example program codes

C fprintf() fscanf()


File handling simply means to open a file and to process it according to the required tasks. Writing data in a file is one of the common feature of file handling. In C, there are various modes that facilitates different ways and features of writing data into a file, including: w, r+, w+, a+, wb, rb+, wb+, or ab+ mode. C also supports some functions to write to a file.

C Write File functions are:

  • C fprintf()
  • C fputs()
  • C fputc()
  • C fputw()

 

C fprintf() function:

To write a file in C, fprintf() function is used.

Syntax:

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

Example  1: Example of fprintf() function.

#include <stdio.h>  
void main()
{  
FILE *f;  
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file handling.\n");
printf ("Data Successfully Written to the file!");
fclose(f);
}

Output

Data Successfully Written to the file!

C Read File:

Reading data from a file is another common feature of file handling. In C, there are various functions that facilitates different ways and features of reading data from a file, including: reading all file data at a single go, reading the file data line by line and even to read the file data character by character.

C Read File functions are:

  • C fscanf()
  • C fgets()
  • C fgetc()
  • C fgetw()

 

❏     C fscanf() function:

To read a file in C, fscanf() function is used.

Syntax:

fscanf(FILE *stream, const char *format [, argument, …])

Example  2: Example of fscanf() function.

#include <stdio.h>  
void main()
{  
FILE *f;  
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file handling.\n");
fclose(f);
 
char arr[50];
f = fopen("file.txt", "r");  
while(fscanf(f, "%s", arr)!=EOF)
{  
printf("%s ", arr);  
}  
fclose(f);  
}

Output

Reading data from a file is a common feature of file handling.
Posted in C   
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki