fgetc()
fgetc()用于一次从文件单个字符获取输入。该函数返回字符的ASCII码读取函数。它返回存在于文件指针指示的位置的字符。读取字符,文件指针将前进到下一个字符。如果指针位于文件末尾或发生错误,则此函数将返回EOF文件。
句法:
int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies
the stream on which the operation is to be performed.
C
// C program to illustate fgetc() function
#include
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);
}
C
// C program to illustate fputc() function
#include
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;
}
输出:
The entire content of file is printed character by
character till end of file. It reads newline character
as well.
使用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
// C program to illustate fputc() function
#include
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
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。