Purpose of getc and putc Functions in C programming
getc and putc Functions in CPurpose of getc and putc Functions in C
The getc and putc functions in C are used for reading and writing single characters from/to a file or stream. They provide a simple and efficient way to handle character-based I/O operations.
getc Function
The getc function is used to read a single character from a file or stream. It returns the next character as an unsigned char cast to an int, or EOF (end-of-file) if the end of the file is reached or an error occurs.
Syntax
int getc(FILE *stream);
Where stream is a pointer to a FILE object that identifies the input stream.
Example Code
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
int ch;
if (file != NULL) {
while ((ch = getc(file)) != EOF) {
putchar(ch); // Output the character to standard output
}
fclose(file); // Close the file
} else {
printf("Error opening file.\n");
}
return 0;
}
In this example:
FILE *file = fopen("example.txt", "r");opens the fileexample.txtfor reading.getc(file)reads characters one by one from the file until EOF is reached.putchar(ch);outputs each character to the standard output (console).fclose(file);closes the file after reading.
putc Function
The putc function is used to write a single character to a file or stream. It returns the character written as an unsigned char cast to an int, or EOF if an error occurs.
Syntax
int putc(int char, FILE *stream);
Where char is the character to be written, and stream is a pointer to a FILE object that identifies the output stream.
Example Code
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file != NULL) {
putc('H', file);
putc('e', file);
putc('l', file);
putc('l', file);
putc('o', file);
putc('\n', file);
fclose(file); // Close the file
printf("Data written to output.txt\n");
} else {
printf("Error opening file.\n");
}
return 0;
}
In this example:
FILE *file = fopen("output.txt", "w");opens the fileoutput.txtfor writing.putc('H', file);writes the character 'H' to the file.- Similarly, other characters are written to the file, including a newline character.
fclose(file);closes the file after writing.
Key Points
- Character-Based I/O:
getcandputcare useful for reading and writing individual characters. - Error Handling: Both functions return EOF to indicate an error or end of file, so always check for this when performing I/O operations.
- File Handling: Ensure the file is successfully opened before using
getcorputc, and close the file after operations to free resources.
fgets or fprintf.
Comments
Post a Comment