在此程序中,我们将学习如何使用C程序查找文本文件中可用的总行数?
该程序将打开一个文件并逐字符读取文件的内容,最后返回文件中的总行数。要计算行数,我们将检查可用的换行符(\ n)。
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
该程序将打开一个文件并逐字符读取文件的内容,最后返回文件中的总行数。要计算行数,我们将检查可用的换行符(\ n)。这将检查所有新行,然后计数并返回计数。
#include<iostream>
using namespace std;
#define FILENAME "test.txt"
int main() {
FILE *fp;
char ch;
int linesCount=0;
//在更多信息中打开文件
fp=fopen(FILENAME,"r");
if(fp==NULL) {
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//逐个字符读取并检查换行
while((ch=fgetc(fp))!=EOF) {
if(ch=='\n')
linesCount++;
}
//关闭文件
fclose(fp);
//打印行数
printf("Total number of lines are: %d\n",linesCount);
return 0;
}