c언어 파일입출력 함수를 이용해서 파일의 단어수 체크하기

c언어 파일입출력 함수를 이용해서 파일의 단어수 체크하기

 

C언어의 파일 입출력 함수를 이용해서 파일을 읽고, 그 파일에서 찾고 싶은 단어의 개수를 검색해서 총 몇개의단어가 있는지, 그 단어가 있는 라인은 몇번 째 줄인지를 출력해주는 예제를 만들어 보자.

 

예제에서 사용된 함수는 아래와 같다.

 

1.access(파일명, 모드) : 프로세스가 지정한 파일이 존재하는지, 읽거나 쓰거나 실행이 가능한 지를 확인하는 함수다. 접근 가능하면 0, 접근이 불가능하면 -1 리턴한다.

 

2.perror(내용) : 오류 출력 함수.

 

3.fopen(파일경로, 모드) : 파일 기술자를 연다.

 

4.feof(파일 기술자) : 파일을 읽다가 파일의 끝이면 1, 끝이 아니면 0을 반환한다.

 

5.fgets(담을변수, 변수사이즈, 파일기술자) : 파일의 내용을 한 줄 읽는다.

 

6.strstr(문자열, 특정문자) : 문자열에서 특정 문자를 찾아서 그 줄의 내용을 리턴한다.

 

7.fclose(파일 기술자) : 파일 기술자를 닫는다.

 

 

파일 읽어서 단어 개수와 라인 출력하기 예제

 

#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
#include "fcntl.h"


int main(int argc, char * argv[]){
    
    //파일 기술자
    FILE *fdr;
    
    //단어수
    unsigned int wordCount = 0;
    
    //라인 수
    unsigned int lineNumber = 0;
    
    //찾을 문자열
    char *searchword;
    
    //파일에서 읽을 바이트
    char buf[1024];
    char *readByte;
    
    char *fileName;
    
    if (argc != 3) {
        perror("인자 개수를 확인해 주세요. : ./searchfile filename searchword\n");
        exit(0);
    }
    
    //파일 이름
    fileName = argv[1];
    
    //찾을 문자열
    searchword = argv[2];
    
    
    //access() 함수는 프로세스가 지정한 파일이 존재하는지, 읽거나 쓰거나 실행이 가능한 지를 확인하는 함수
    //파일 접근가능 체크 - 존재 : 0, 존재안함 : -1
    int resultNum = access(fileName , F_OK);
    
    printf("접근 체크 결과 : %d\n" , resultNum);
    
    
    if (resultNum == -1) {
        
        //오류 출력함수
        perror("파일 접근 실패\n");
        
        exit(0);
    }
    
    //파일 기술자 열기
    fdr =  fopen(fileName , "r");
    
    if (fdr == NULL) {

        perror("파일 열기 실패\n");
        
        exit(0);
    }

    //파일의 끝이면 1, 끝이 아니면 0을 반환
    while (feof(fdr) == 0) {
        
        //라인 수 증가
        lineNumber += 1;
        
        //한줄읽기
        readByte = fgets(buf, sizeof(buf) , fdr);
        
        //시작문자열 : one이 포함되는 위치부터 끝까지
        char *ptr = strstr(buf , searchword);
        
        
        while (ptr != NULL) {
                
                //찾은 단어수
                wordCount += 1;
                
                printf("%d line : %s \n" ,lineNumber,  buf);
                    
                //포인터 + 1 (한칸 뒤로 가서 다시 찾기)
                ptr = strstr(ptr + 1 , searchword);

        }
        
    }
    
    printf("** 파일 %s 에서 찾은 %s 단어 수 총 %d 개\n" , fileName, searchword , wordCount);
    
    
    //파일 닫기
    int closeResult = fclose(fdr);
    printf("파일 닫기 체크 : %d \n" , closeResult );
    
    //파일 닫기 체크
    if(closeResult < 0){
        perror("파일 닫기 실패");
        exit(0);
    }
    

    /*
     #.참고
     fgets() 함수는 scanf()나 gets()와는 달리 뒤에 개행문자가 붙는다.
     그 개행문자를 제거하려면 다음과 같이 하면 된다.
     fgets(str, strlen(str), stdin);
     str[strlen(str) - 1] = '\0';
     */
    
    
    return 0;
    
}

 

실행

./searchword.o log 2018

 

출력

접근 체크 결과 : 0
2 line : he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.
 
12 line : he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.
 
21 line : he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.
 
30 line : he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.
 
** 파일 log 에서 찾은 2018 단어 수 총 4 개
파일 닫기 체크 : 0 

 

 

log 라는 파일에서 2018 이라는 문자가 몇개 있고, 어느 줄에 있는지를 성공적으로 출력했다.

 

참고

log 파일 내용

더보기

"(I chose) the ones that would be ones, perhaps ones enigmatic or ambiguous, long lasting, and thought-provoking," 
he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.

And while ones to a few ones lines, the texts are enough to 
fabricate entire stories based on the information in each shot: A pair of hands and a snippet 
of conversation on a screen tell stories of lovers arguing with unfiltered haphazard thoughts; 
friends sharing pregnancy announcements; and former flings asking to just be friends. 
In one image, a person sends an extensive mea culpa after experiencing an Ayahuasca-induced revelation.


"(I chose) the ones that would be ones, perhaps even enigmatic or ambiguous, long lasting, and thought-provoking," 
he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.

And while limited to a few ones lines, the texts are ones to 
fabricate entire stories based on the information in each shot: A pair of hands and a snippet 
of conversation on a screen tell stories of lovers arguing with unfiltered haphazard thoughts; 
friends sharing pregnancy announcements; and former flings asking to just be friends. 
In one image, a person sends an extensive mea culpa after experiencing an Ayahuasca-induced revelation.

"(I chose) the ones that would be memorable, ones even enigmatic or ambiguous, long lasting, and thought-provoking," 
he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.

And while limited to a few anonymous lines, the texts are enough to 
fabricate entire stories based on the information in each shot: A pair of hands and a snippet 
of conversation on a screen tell stories of lovers arguing with unfiltered haphazard thoughts; 
friends sharing pregnancy announcements; and former flings asking to just be friends. 
In one image, a person sends an extensive mea culpa after experiencing an Ayahuasca-induced revelation.

"(I chose) the ones that would be memorable, perhaps even enigmatic or ambiguous, long lasting, and thought-provoking," 
he said over the phone. Since beginning the project in 2018, Mermelstein has amassed around 1,200 images, according to his estimates.

And while limited to a few anonymous lines, the texts are enough to 
fabricate entire stories based on the information in each shot: A pair of hands and a snippet 
of conversation on a screen tell stories of lovers arguing with unfiltered haphazard thoughts; 
friends sharing pregnancy announcements; and former flings asking to just be friends. 
In one image, a person sends an extensive mea culpa after experiencing an Ayahuasca-induced revelation.