Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C นับจำนวนบรรทัดในไฟล์ (Text File Line Count)


เปิดไฟล์โหมดอ่าน นับจำนวน newline (\n) เพื่อหาจำนวนบรรทัด

โปรแกรมที่ 1: นับบรรทัดไฟล์ที่มีอยู่แล้ว

#include <stdio.h>
#define FILENAME "Employee Details.txt"

int main() {
    FILE *fp;
    char ch;
    int lines = 0;
    
    fp = fopen(FILENAME, "r");
    if (fp == NULL) {
        printf("File not found!\n");
        return -1;
    }
    
    while((ch = getc(fp)) != EOF) {
        if(ch == '\n') lines++;
    }
    fclose(fp);
    
    printf("Total lines: %d\n", lines);
    return 0;
}

ผลลัพธ์

Total number of lines are: 3

โปรแกรมที่ 2: สร้างไฟล์ใหม่ แล้วนับบรรทัด

#include <stdio.h>
#define FILENAME "sample.txt"

int main() {
    FILE *fp;
    char ch;
    int lines = 0;
    
    // เขียนไฟล์ก่อน
    fp = fopen(FILENAME, "w");
    printf("Enter text (Ctrl+Z to end):\n");
    while((ch = getchar()) != EOF) fputc(ch, fp);
    fclose(fp);
    
    // อ่านนับบรรทัด
    fp = fopen(FILENAME, "r");
    while((ch = getc(fp)) != EOF) {
        if(ch == '\n') lines++;
    }
    fclose(fp);
    
    printf("Total lines: %d\n", lines);
    return 0;
}

ผลลัพธ์

enter text press ctrl+z of the end
Hi welcome to Tutorials Point
C Programming Question & answers
^Z
Total number of lines are: 2