如何使用 C 語言將內容列印到檔案?


我們可以編寫一個 C 程式,將一些內容列印到檔案中,然後列印以下內容:

  • 輸入檔案中的字元數。
  • 反轉輸入檔案中的字元。

首先,嘗試透過以寫模式開啟檔案來儲存檔案中的字元數。

為了將資料輸入檔案,我們使用如下所述的邏輯:

while ((ch = getchar( ))!=EOF) {//after enter data press cntrl+Z to terminate
   fputc(ch, fp);
}

藉助 ftell、rewind、fseek 函式,我們可以反轉我們已經輸入檔案的內容。

示例

下面給出了一個 C 程式,用於將一些內容列印到檔案中,並列印輸入檔案中的字元數和反轉字元:

 Live Demo

#include<stdio.h>
int main( ){
   FILE *fp;
   char ch;
   int n,i=0;
   fp = fopen ("reverse.txt", "w");
   printf ("enter text press ctrl+z of the end");
   while ((ch = getchar( ))!=EOF){
      fputc(ch, fp);
   }
   n = ftell(fp);
   printf ( "No. of characters entered = %d
", n);    rewind (fp);    n = ftell (fp);    printf ("fp value after rewind = %d
",n);    fclose (fp);    fp = fopen ("reverse.txt", "r");    fseek(fp,0,SEEK_END);    n = ftell(fp);    printf ("reversed content is
");    while(i<n){       i++;       fseek(fp,-i,SEEK_END);       printf("%c",fgetc(fp));    }    fclose (fp);    return 0; }

輸出

當執行上述程式時,它產生以下結果:

enter text press ctrl+z of the end
TutorialsPoint
^Z
No. of characters entered = 18
fp value after rewind = 0
reversed content is
tnioPslairotuT

更新日期:11-Mar-2021

194 次瀏覽

開啟你的職業生涯 生涯

完成課程,獲得認證

開始
廣告