C fputc()
and fgetc()
Functions
Syntax
int fputc(int c, FILE *stream);
int fgetc(FILE *stream);
Example
#include<stdio.h>
int main(){
FILE *fp;
char str[] = "Fputc and Fgetc Functions Example";
char buffer[50];
fp = fopen("file.txt", "w+");
if(fp == NULL) {
printf("The file cannot be opened.\n");
return 0;
}
fputs(str, fp);
fseek(fp, 0, SEEK_SET);
while(fgetc(fp) != EOF) {
printf("%c", fgetc(fp));
}
fclose(fp);
return 0;
}
Output
The output of the above example will be:
Fpc ndFcFntosExample
Explanation
The fputc()
function is used to write a character to a file. The function takes two arguments, the character to be written and the file pointer of the file to which it is to be written. If the function is successful, it returns the value of the written character. Otherwise, it returns EOF
.
The fgetc()
function is used to read a character from a file. The function takes only one argument, the file pointer of the file from which the character is to be read. If the function is successful, it returns the character. Otherwise, it returns EOF
.
Use
The fputc()
and fgetc()
functions are used to write and read a single character to/from a file, respectively. These functions can be used to read and write text or binary files in C.
Important Points
- The
fputc()
function writes a single character to a file. - The
fgetc()
function reads a single character from a file. - These functions are available in the
stdio.h
header file. - In binary files, the
fputc()
andfgetc()
functions can write and read binary data, respectively. - The
stdio.h
header file provides various other functions such asfgets()
,fputs()
,fprintf()
, andfscanf()
that can be used to read and write strings, formatted data, and more.
Summary
The fputc()
and fgetc()
functions are commonly used for reading and writing individual characters to and from a file, respectively, in C. The stdio.h
header file provides many other useful file I/O functions that are commonly used in C programming. Understanding the basic syntax and use cases for these functions can greatly enhance the functionality of your C programs that require file I/O operations.