이 프로그램에서는 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;
//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;
}