fgetc()
fgetc()用于一次从文件单个字符获取输入。此函数返回该函数读取的字符数。它返回存在于文件指针指示的位置的字符。读取字符后,文件指针前进到下一个字符。如果指针位于文件末尾或发生错误,则此函数将返回EOF文件。
用法:
int fgetc(FILE *pointer) pointer: pointer to a FILE object that identifies the stream on which the operation is to be performed.
// C program to illustate fgetc() function
#include <stdio.h>
int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");
// Return if could not open file
if (fp == NULL)
return 0;
do
{
// Taking input single character at a time
char c = fgetc(fp);
// Checking for end of file
if (feof(fp))
break ;
printf("%c", c);
} while(1);
fclose(fp);
return(0);
}
输出:
The entire content of file is printed character by character till end of file. It reads newline character as well.
Using fputc()
fputc()用于一次将单个字符写入给定文件。它将给定字符写入文件指针指示的位置,然后前进文件指针。
该函数返回在成功执行写入操作的情况下写入的字符,否则在返回错误EOF的情况下返回。
用法:
int fputc(int char, FILE *pointer) char: character to be written. This is passed as its int promotion. pointer:pointer to a FILE object that identifies the stream where the character is to be written.
// C program to illustate fputc() function
#include<stdio.h>
int main()
{
int i = 0;
FILE *fp = fopen("output.txt","w");
// Return if could not open file
if (fp == NULL)
return 0;
char string[] = "good bye", received_string[20];
for (i = 0; string[i]!='\0'; i++)
// Input string into the file
// single character at a time
fputc(string[i], fp);
fclose(fp);
fp = fopen("output.txt","r");
// Reading the string from file
fgets(received_string,20,fp);
printf("%s", received_string);
fclose(fp);
return 0;
}
输出:
good bye
执行fputc()时,将字符串变量的字符一一写入文件中。当我们从文件中读取行时,我们得到与输入的相同的字符串。
注:本文由纯净天空筛选整理自 fgetc() and fputc() in C。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。