C에서 feof 함수 사용

이 기사에서는 C에서feof
기능을 사용하는 방법에 대한 몇 가지 방법을 설명합니다.
feof
기능을 사용하여 C의 파일 스트림에서 파일 끝 표시기를 확인합니다
feof
함수는<stdio.h>
헤더에 정의 된 C 표준 입력 / 출력 라이브러리의 일부입니다. feof
함수는 주어진 파일 스트림에서 파일 끝 표시기를 확인하고EOF
가 설정된 경우 0이 아닌 정수를 리턴합니다. FILE
포인터를 유일한 인수로 사용합니다.
다음 예에서는feof
가 0을 반환 할 때까지 호출되어 파일 스트림이EOF
에 도달하지 않았 음을 의미하는getline
함수를 사용하여 파일을 한 줄씩 읽을 때를 보여줍니다. 조건문에서getline
함수 반환 값을 확인하고 성공한 경우에만printf
를 호출하여 읽기 행을 출력합니다.
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> const char* filename = "input.txt"; int main(void) { FILE* in_file = fopen(filename, "r"); if (!in_file) { perror("fopen"); exit(EXIT_FAILURE); } struct stat sb; if (stat(filename, &sb) == -1) { perror("stat"); exit(EXIT_FAILURE); } char* contents = NULL; size_t len = 0; while (!feof(in_file)) { if (getline(&contents, &len, in_file) != -1) { printf("%s", contents); } } fclose(in_file); exit(EXIT_SUCCESS); }
feof
및ferror
함수를 사용하여 C에서 파일 스트림의 유효한 위치 테스트
또는feof
를 사용하여 파일 내용을 읽기 전에 파일 스트림 위치를 테스트 할 수 있습니다. 이 경우,stat
함수 호출로 검색된 파일의 크기를 가져 오는fread
호출을 사용하여 파일을 읽습니다. 읽기 바이트를 저장할 버퍼는malloc
함수를 사용하여 힙에 할당됩니다. 또한 조건문에ferror
기능을 포함하여EOF
표시기와 함께 파일 스트림의error
상태를 테스트했습니다.
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> const char* filename = "input.txt"; int main(void) { FILE* in_file = fopen(filename, "r"); if (!in_file) { perror("fopen"); exit(EXIT_FAILURE); } struct stat sb; if (stat(filename, &sb) == -1) { perror("stat"); exit(EXIT_FAILURE); } char* file_contents = malloc(sb.st_size); if (!feof(in_file) && !ferror(in_file)) fread(file_contents, 1, sb.st_size, in_file); printf("read data: %s\n", file_contents); free(file_contents); fclose(in_file); exit(EXIT_SUCCESS); }
ferror
도 I/O 라이브러리의 일부이며FILE
포인터 객체에서 호출 할 수 있습니다. 오류 비트가 파일 스트림에 설정되어 있으면 0이 아닌 표시기를 반환합니다. 세 가지 예제 모두filename
변수로 지정된 파일의 내용을 인쇄합니다. 앞의 예시 코드에서 우리는printf
함수를 사용하여 저장된 내용을 출력하지만, 더욱 잘못하기 쉬운 방법은 fwrite
로 호출하는 것으로, 주어진 바이트 수를 네 번째 파라미터가 지정한 FILE
흐름 속에 인쇄할 수 있다.
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> const char* filename = "input.txt"; int main(void) { FILE* in_file = fopen(filename, "r"); if (!in_file) { perror("fopen"); exit(EXIT_FAILURE); } struct stat sb; if (stat(filename, &sb) == -1) { perror("stat"); exit(EXIT_FAILURE); } char* file_contents = malloc(sb.st_size); if (!feof(in_file) && !ferror(in_file)) fread(file_contents, 1, sb.st_size, in_file); fwrite(file_contents, 1, sb.st_size, stdout); free(file_contents); fclose(in_file); exit(EXIT_SUCCESS); }
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook