解釋C語言中檔案的追加模式操作


檔案是記錄的集合,或者說是硬碟上永久儲存資料的地方。

檔案的必要性

  • 程式終止時,所有資料都會丟失。

  • 將資料儲存在檔案中,即使程式終止,資料也能保留。

  • 如果要輸入大量資料,通常需要花費大量時間。

  • 我們可以使用少量命令輕鬆訪問檔案的內容。

  • 您可以輕鬆地將資料從一臺計算機移動到另一臺計算機,而無需更改。

  • 使用C命令,我們可以以不同的方式訪問檔案。

檔案操作

C程式語言中的檔案操作如下:

  • 檔案命名
  • 開啟檔案
  • 從檔案讀取
  • 寫入檔案
  • 關閉檔案

語法

宣告檔案指標的語法如下:

FILE *File pointer;

例如,FILE * fptr;

命名和開啟檔案指標的語法如下:

File pointer = fopen ("File name", "mode");

例如,要以追加模式開啟檔案,請使用以下語法:

FILE *fp;
fp =fopen ("sample.txt", "a");

如果檔案不存在,則會建立一個新檔案。

如果檔案存在,則將當前內容新增到舊內容中。

程式

以下是C程式,用於以追加模式開啟檔案並計算檔案中存在的行數:

 線上演示

#include<stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
   FILE *fp;
   char ch;
   int linesCount=0;
   //open file in read more
   fp=fopen(FILENAME,"r");
   if(fp==NULL){
      printf("File \"%s\" does not exist!!!
",FILENAME);       return -1;    }    //read character by character and check for new line    while((ch=getc(fp))!=EOF){       if(ch=='
')          linesCount++;    }    //close the file    fclose(fp);    //print number of lines    printf("Total number of before adding lines are: %d
",linesCount);    fp=fopen(FILENAME,"a"); //open fine in append mode    while((ch = getchar())!=EOF){       putc(ch,fp);    }    fclose(fp);    fp=fopen(FILENAME,"r");    if(fp==NULL){       printf("File \"%s\" does not exist!!!
",FILENAME);       return -1;    }    //read character by character and check for new line    while((ch=getc(fp))!=EOF){       if(ch=='
')          linesCount++;    }    //close the file    fclose(fp);    //print number of lines    printf("Total number of after adding lines are: %d
",linesCount);    return 0; }

輸出

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

Total number of lines before adding lines are: 3
WELCOME to Tutorials
Its C Programming Language
^Z
Total number of after adding lines are: 8

更新於:2021年3月24日

597 次檢視

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.