fputc() fgetc() in C
0 238
fputc() in C
Description:
The fputc() function in C is used to write a single character to a file specified by the stream.
Syntax of fputc() in C:
int fputc(int character, FILE *stream);
The character parameter specifies the character to write, while the stream is a pointer to the FILE object indicating the file stream.
stream is a pointer to the FILE object that points to the file stream.
Return Value:
On success, fputc() returns the character written as an unsigned char cast to an int.
On failure, it returns EOF.
Example:
#include<stdio.h>int main() { FILE *fp; // Open a file named "output.txt" in write mode fp = fopen("output.txt", "w"); // Check if the file opened successfully if (fp != NULL) { // Write a character 'A' to the file fputc('A', fp); // Write a newline character '\n' to the file fputc('\n', fp); // Close the file fclose(fp); printf("Character written to file successfully.\n"); } else { printf("Error opening file.\n"); } return 0; }
Output:
Error opening file.
fgetc() in C
Description:
The fgetc() function in C is used to read a single character from a file specified by the stream.
syntax of fgetc()in C:
int fgetc(FILE *stream);
stream: Pointer to the FILE object that identifies the stream from which to read.
Return Value:
On success, fgetc() returns the character read as an unsigned char cast to an int.
On reaching the end-of-file, it returns EOF.
On failure, it returns EOF.
Example:
#include<stdio.h>int main() { FILE *fp; int ch; // Open a file named "input.txt" in read mode fp = fopen("input.txt", "r"); // Check if the file opened successfully if (fp != NULL) { // Read characters from the file until EOF (End-Of-File) is reached while ((ch = fgetc(fp)) != EOF) { // Print the read character to the console putchar(ch); } // Close the file fclose(fp); printf("\nFile reading completed.\n"); } else { printf("Error opening file.\n"); } return 0; }
Output:
Error opening file.
Share:
Comments
Waiting for your comments