ในโปรแกรมนี้ เราจะมาเรียนรู้วิธีหาจำนวนบรรทัดทั้งหมดในไฟล์ข้อความโดยใช้โปรแกรม C?
โปรแกรมนี้จะเปิดไฟล์และอ่านเนื้อหาของไฟล์ทีละอักขระ และสุดท้ายจะคืนค่าจำนวนบรรทัดทั้งหมดในไฟล์ ในการนับจำนวนบรรทัด เราจะตรวจสอบอักขระ Newline (\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
คำอธิบาย
โปรแกรมนี้จะเปิดไฟล์และอ่านเนื้อหาของไฟล์ทีละอักขระ และสุดท้ายจะคืนค่าจำนวนบรรทัดทั้งหมดในไฟล์ ในการนับจำนวนบรรทัด เราจะตรวจสอบอักขระ Newline (\n) ที่มีอยู่ การดำเนินการนี้จะตรวจสอบบรรทัดใหม่ทั้งหมดแล้วนับ จากนั้นจึงคืนค่าการนับ
ตัวอย่าง
#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!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=fgetc(fp))!=EOF) {
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
}