C 语言编程中的 fputc

C 语言的 fputc 函数可用于将字符写入指定流中文件的当前位置,然后前移指针位置。本文通过一个示例展示了如何使用 fputc 将字符、字符数组(字符串)或字符串数据写入文件。使用 fputc 函数来写入完整的字符串,该函数的语法如下

int fputc(int char, FILE *stream)
or 
int fputc(int char, <File Pointer>)

我们使用空文件来演示 fputc 函数。在使用 fputc 函数之前,您必须包含 #include<stdio.h> 头文件。

C 语言编程中的 fputc 示例

fputc 函数将字符写入用户指定的文件。这个 C 语言程序将帮助您理解这一点。

#include <stdio.h> 
#include<string.h>

int main()
{
   FILE *fileAddress;
   fileAddress = fopen("sample.txt", "w");
   char name[50] = "Tutorial Gateway";
   int i;
   int len = strlen(name);

   if (fileAddress != NULL) {
	for (i = 0; i < len; i++) {
           printf("Character we ar writing to the File = %c \n", name[i]);
	   // Let us use
	   fputc (name[i], fileAddress);
	}
	printf("\n We have written the Name successfully");
	fclose(fileAddress);		
   }
   else {
  	  printf("\n Unable to Create or Open the Sample.txt File");
   }
   return 0;
}
FPUTC File Example

让我们打开文件,看看它是否返回了这些字符。

Text file Result