C語言程式如何統計檔案中行數?


在本教程中,我們將學習如何使用 C 語言程式查詢文字檔案中可用的總行數?

此程式將開啟一個檔案,逐個字元讀取檔案的內容,最後返回檔案中的總行數。為了統計行數,我們將檢查可用的換行符(
) 字元。

Input:
File "test.text"
   Hello friends, how are you?
   This is a sample file to get line numbers from the file.
Output:
Total number of lines are: 2

說明

此程式將開啟一個檔案,逐個字元讀取檔案的內容,最後返回檔案中的總行數。為了統計行數,我們將檢查可用的換行符(
) 字元。這將檢查所有換行符並計數,然後返回計數。

示例

#include<iostream>
using namespace std;
#define FILENAME "test.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=fgetc(fp))!=EOF) {       if(ch=='
')          linesCount++;    }    //close the file    fclose(fp);    //print number of lines    printf("Total number of lines are: %d
",linesCount);    return 0; }

更新日期: 2019-08-20

8K+ 瀏覽

開啟您的 職業

完成課程並獲得認證

開始
廣告