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