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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。