getc(), putc(),fgetc() and fputc() are the character input output functions. As in the string manipulation gets( ) function is used to read a string and puts( ) is used to write the string, in the same way in file management system getc() and putc() is used to read and write a character in the file respectively. These two functions take the syntax as:
variable=getc(file_pointer);
putc(variable,file_pointer);
As a practical use of these character input output functions, we can read line of text in lowercase and convert it to uppercase, as demonstrated in the following example.
Use of getc() and putc() functions to read a line of text in lowercase and store in a data file after converting it to uppercase.
Example 1
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
main()
{
char ch;
FILE *fp;
fp=fopen(“file1.txt”,”a+”);
if (fp==NULL)
{
printf(“cannot open file”);
fclose(fp);
exit(1);
}
do
{
ch=toupper(getchar());
putc(ch,fp);
}while(ch!=’\n’);
clrscr();
rewind(fp);
while((ch=getc(fp)!=EOF)
printf(“%c”,ch);
fclose(fp);
getch();
}
No Comments