프로그래밍 언어/C, C++ 다양한 예시들
[C 언어] 텍스트 파일의 총 개행 수 구하기
UltraLowTemp-Physics
2021. 2. 6. 02:03
아래와 같이 grade.txt와 같은 텍스트 파일이 있다고 하자. 이때, 해당 파일의 총 개행 수를 구해보자.
파일: grade.txt
0001 Tommy 22 A
0002 Grace 25 B
0003 Landau 53 A
0004 Tim 19 A
0005 Einstien 66 D
0006 Newton 100 A
0007 Hawking 50 C
0008 Feynman 20 B
0009 Bohr 35 A
코드
#include <stdio.h>
#include <stdlib.h>
int main(void){
int count_line = 0;
char *f_name = "./grade.txt";
char tmp;
FILE *open_file;
open_file = fopen(f_name, "r");
while(fscanf(open_file, "%c", &tmp )!= EOF){
if(tmp == '\n'){
count_line++;
}
}
fseek(open_file, 0L, SEEK_SET);
printf("%d\n", count_line);
return 0;
}
- 파일을 연 후, fscanf로 파일의 각 문자를 하나씩 tmp에 복사를 한다.
- 만일 복사된 문자가 개행 문자("\n")일 경우 count_line을 1씩 증가시킨다.
- 복사한 문자가 파일 종료 문자 (EOF)를 만날 경우, while 문을 빠져 나온다.