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+ 浏览

开启您的 职业

完成课程并获得认证

开始
广告
© . All rights reserved.