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;
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP