吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C 中的 fgetc() 和 fputc()

C 中的 fgetc() 和 fputc()

来源:网络 | 更新时间:2022-01-25 21:59:11
fgetc() fgetc() 用于一次从文件中获取单个字符的输入。该函数返回函数读取的字符的 ASCII 码。它返回文件指针指示的位置处的字符。读完字符后,文件指针前进到下一个字符。如果指针位于文件末尾或发生错误,则此函数返回 EOF 文件。  语法: 
int fgetc(FILE *pointer)
pointer: 指向标识的 FILE 对象的指针要对其执行操作的流。
// C program to illustrate 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. 使用 fputc() fputc() 用于一次将单个字符写入给定文件。它将给定字符写入文件指针指示的位置,然后前进文件指针。  此函数在写入操作成功的情况下返回写入的字符,否则在错误的情况下返回 EOF。  语法: 
int fputc(int char, FILE *pointer) 
char:要写入的字符。这作为其 int 提升传递。
pointer:指向 FILE 对象的指针,该对象标识要写入字符的流。
// C program to illustrate 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]!=''; 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() 时,字符串变量的字符被一个一个写入文件。当我们从文件中读取该行时,我们会得到与输入相同的字符串。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com