C getc and putc methods example:
In C programming language, getc and putc methods are used for reading and writing contents from a file. We can use these functions to read a character from a file or write a character to a file.
In this post, we will learn how to use getc and putc methods with definitions and examples.
getc():
getc is defined as like below:
int getc(FILE *f)
It takes one parameter, the file pointer, or the file to read the content.
It returns one integer value, i.e. the character it reads. If an error occurs, it returns EOF. We can convert the integer value to character.
putc():
putc is defined as like below:
int putc(int ch, FILE *f)
It write one character to a stream. It takes two parameters. ch is the character to write and f is a file pointer defining the stream.
It returns the character it wrote to the stream.
If any error occurs, it returns EOF.
Example of getc() and putc() to copy file content to a new file:
Let’s use getc and putc to copy the contents of one file to another file. For that, we will create two FILE pointers, open the files in read and write mode and using a loop, we will read and write the contents.
Below is the complete program:
#include <stdio.h>
int main()
{
char ch;
FILE *readFile;
FILE *writeFile;
readFile = fopen("original.md", "r");
writeFile = fopen("copy.md", "w");
while ((ch = getc(readFile)) != EOF)
{
putc(ch, writeFile);
}
fclose(readFile);
fclose(writeFile);
return 1;
}
Here,
- It is reading the content from the file original.md and writing that to copy.md.
- readFile and writeFile are two FILE pointers to hold the reference for original.md and copy.md. If copy.md is not there, it will create that file.
- ch is a char variable to hold the currently reading character from the reading file.
- The while loop reads the content of the original.md, one by one and it reads all characters until EOF is reached. For each character it reads, it writes that to writeFile using putc.
- Once the reading/writing is done, it closes the files by using fclose.
If you run this program, it will copy all the content of original.md to copy.md.
You might also like:
- C program to reverse a string without using any library function(strrev)
- How to use strstr in C with example
- How to split a string in C using strtok library function
- C program to print all words in a string ends with a specific character
- C program to convert hour to minute and seconds value
- C nanosleep method explanation with example
- How to delete an empty directory in C