Welcome to our comprehensive guide on the fgetc() function in C programming! By the end of this lesson, you'll have a solid understanding of this essential function and be able to use it confidently in your own projects. Let's dive in!
The fgetc() function is a part of the standard input/output library in C and is used to read one character at a time from a stream. This function is particularly useful when you need to process input one character at a time, such as reading a line of text or handling user input.
int fgetc(FILE *fp);The fgetc() function takes a FILE *fp as an argument, which is a pointer to a file stream. It returns the next character from the specified stream or the EOF (End Of File) value if the end of the file is reached.
Let's create a simple program that reads characters from the keyboard and displays them on the screen.
#include <stdio.h>
int main() {
char ch; // Declare a character variable
// Infinite loop to read characters
while ((ch = fgetc(stdin)) != EOF) {
printf("%c", ch); // Print the read character
}
return 0;
}In this example, we declare a variable ch to store the character read by fgetc(). The loop continues until the end of the file is reached (EOF), and it prints the character on the screen.
Now, let's modify the previous example to read characters from a file instead of the keyboard.
#include <stdio.h>
int main() {
FILE *file; // Declare a file pointer
char ch;
// Open the file in read mode
file = fopen("example.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}
// Infinite loop to read characters
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch); // Print the read character
}
// Close the file
fclose(file);
return 0;
}In this example, we open a file named example.txt in read mode using the fopen() function. We then read characters from the file using fgetc() and print them on the screen. Don't forget to close the file using fclose() when you're done!
What does the `fgetc()` function do in C programming?
And that's it for this lesson on the fgetc() function in C programming! As you practice using this function, you'll find it very useful for reading and processing input in your programs. In the next lesson, we'll cover more functions from the standard I/O library to help you become even more proficient in C programming. Happy coding! 😊