Latest web development tutorials

C 庫函數– fputc()

C 標準庫 - <stdio.h> C標準庫- <stdio.h>

描述

C庫函數int fputc(int char, FILE *stream)把參數char指定的字符(一個無符號字符)寫入到指定的流stream中,並把位置標識符往前移動。

聲明

下面是fputc() 函數的聲明。

int fputc(int char, FILE *stream)

參數

  • char --這是要被寫入的字符。該字符以其對應的int 值進行傳遞。
  • stream --這是指向FILE對象的指針,該FILE對象標識了要被寫入字符的流。

返回值

如果沒有發生錯誤,則返回被寫入的字符。 如果發生錯誤,則返回EOF,並設置錯誤標識符。

實例

下面的實例演示了fputc() 函數的用法。

#include <stdio.h>

int main ()
{
   FILE *fp;
   int ch;

   fp = fopen("file.txt", "w+");
   for( ch = 33 ; ch <= 100; ch++ )
   {
      fputc(ch, fp);
   }
   fclose(fp);

   return(0);
}

讓我們編譯並運行上面的程序,這將在當前目錄中創建文件file.txt ,它的內容如下:

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd

現在讓我們使用下面的程序查看上面文件的內容:

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}

C 標準庫 - <stdio.h> C標準庫- <stdio.h>