"fgetc()" is a standard library function in C Language used for reading characters from a file.
It reads the next character from the specified input file stream and advances the file position indicator to the next character.
File Input: `fgetc()` function allows us to read individual characters from files and process input character-by-character.
Error Handling: The return value of `fgetc()` can be used to check for errors during the read operation.
Return Value: `fgetc()` returns the character read as an unsigned char cast to an int, or EOF (End of File) to indicate the end of the file or an error.
int fgetc(FILE *stream);
stream: A pointer to a "FILE" object that identifies the input stream.
The "fgetc()" function returns the next character from the input stream as an unsigned "char" cast to an "int", or EOF (defined in "stdio.h") to indicate the end of the file or an error.
#include <stdio.h> int main() { FILE *file; int ch; // Open the file in read mode file = fopen("example.txt", "r"); // Check if file opened successfully if (file == NULL) { perror("Error opening file"); return 1; } // Read characters from the file until EOF is encountered while ((ch = fgetc(file)) != EOF) { // Do something with the character, such as printing it putchar(ch); } // Close the file fclose(file); return 0; }
"fgetc()" is used in a loop to read characters from the file "example.txt" until EOF is returned, indicating the end of the file.
Each character read is printed to the standard output using "putchar()". Finally, the file is closed using "fclose()".
#include <stdio.h> int main() { FILE *sourceFile, *destFile; int ch; // Open the source file in read mode sourceFile = fopen("source.txt", "r"); if (sourceFile == NULL) { perror("Error opening source file"); return 1; } // Open the destination file in write mode destFile = fopen("destination.txt", "w"); if (destFile == NULL) { perror("Error opening destination file"); fclose(sourceFile); return 1; } // Copy contents character by character while ((ch = fgetc(sourceFile)) != EOF) { fputc(ch, destFile); } // Close both files fclose(sourceFile); fclose(destFile); printf("File copied successfully.\n"); return 0; }
Reads characters from one file and writes them to another, effectively copying the contents of one file to another: