CodesJava

Easy learning with example program codes

C fputc() fgetc()


C Write File:

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 fputc() function:

To write a single character into a file in C, fputc() function is used.

Syntax:

fputc(char, FILE *stream)

Example  1: Example of fputc() function.

#include <stdio.h>  
void main()
{  
FILE *f;  
f = fopen("file.txt", "w");
fputc('Z',fp);
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 fgetc() function:

To read a single character from a file in C, fgetc() function is used.

Syntax:

fgetc(FILE *stream)

Example  2: Example of fgetc() 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 ch;
f = fopen("file.txt", "r");  
while((ch=fgetc(f))!=EOF)
{  
printf("%c",ch);  
}  
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