解釋C語言中檔案的讀取模式操作


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

檔案的作用

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

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

  • 如果您想輸入大量資料,通常需要花費大量時間才能全部輸入。

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

  • 您可以輕鬆地在計算機之間移動資料,而無需更改。

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

檔案操作

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

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

語法

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

FILE *File pointer;

例如,FILE * fptr;

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

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

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

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

如果檔案不存在,則fopen函式返回NULL值。

如果檔案存在,則成功從檔案讀取資料。

示例

以下是開啟檔案以進行讀取並計算檔案中存在的行數的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"); // already existing need to be open in read mode
   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 lines are: %d
",linesCount);    return 0; }

輸出

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

Total number of lines are: 3

更新於: 2021年3月24日

823 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告