C 庫函數– putc()
描述
C庫函數int putc(int char, FILE *stream)把參數char指定的字符(一個無符號字符)寫入到指定的流stream中,並把位置標識符往前移動。
聲明
下面是putc() 函數的聲明。
int putc(int char, FILE *stream)
參數
- char --這是要被寫入的字符。該字符以其對應的int 值進行傳遞。
- stream --這是指向FILE對象的指針,該FILE對象標識了要被寫入字符的流。
返回值
該函數以無符號char 強制轉換為int 的形式返回寫入的字符,如果發生錯誤則返回EOF。
實例
下面的實例演示了putc() 函數的用法。
#include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("file.txt", "w"); for( ch = 33 ; ch <= 100; ch++ ) { putc(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); }