계속 오류가 뜹니다...

조회수 990회

several cities in Korea has university and college campuses in

downtown. The one located in Anam-dong is Korea University

established in 1905. ...

ranked 104th in the world and 19th in the Asia rankings, Korea

University has a student body of nearly 37,500, and, of its faculty of

1,500, over 95% hold a PhD or equivalent within ...

라는 내용을 가진 topuniv.txt 파일을 열어서 문자열 Korea University 를 찾고 그 문자열이 있는 줄이 몇번 째 줄인지와 그 문자열을 포함한 줄을 output1.txt 파일로 저장하는 프로그램 입니다. 밑은 제가 짠 프로그램입니다. 디버그 할 때는 문제가 발생하지 않는데 실행하면 오류가 뜨네요... 어디가 틀린 걸까요 ㅠㅠ..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#pragma warning(disable:4996)
void find_single_line(char* input_file, char* output_file)
{
    FILE * input = fopen("input_file", "r");
    FILE * output = fopen("output_file", "w");
    int ln = 0;
    char line[BUFSIZ];
    int len;

    while (1) {

        fgets(line, BUFSIZ, input);
        len = strlen(line);

        if (len == 0)
            break;

        if (strstr(line, "Korea University") != 0)
            ln++;
    }

    /* int ln: line number at which Korea University is found */
    /* char line[]: string buffer containing the line */
    fprintf(output, "At %d: %s", ln, line);
}

int main()
{
    char input_file[] = "topuniv.txt";
    char output1_file[] = "output1.txt";
    find_single_line(input_file, output1_file);
}




*

또 위의 문장을 보면 Korea University가 줄 바꿈 되어서 적혀있는데

(ranked 104th in the world and 19th in the Asia rankings, **Korea

University** has a student body of nearly 37,500, and, of its faculty of)

그런 경우에 각 단어가 몇번째 줄에 있는지, 두 단어가 포함되어있는 두 줄을 출력하는 법도 알려주시면 감사하겠습니다...

1 답변

  • 7번째 줄과 8번째 줄이 잘못되었네요.

    FILE * input = fopen(**"input_file"**, "r");
    FILE * output = fopen(**"output_file"**, "w");
    

    에서 큰 따옴표를 뺀

    FILE * input = fopen(**input_file**, "r");
    FILE * output = fopen(**output_file**, "w");
    

    로 바꾸시면 세그멘테이션 에러는 발생하지 않습니다.

    세그멘테이션 오류는 프로그램이 접근할 수 없는 메모리에 접근하고자 할때 발생하는 에러입니다. fopen()으로 파일에 접근할때 해당하는 파일이 없으면 fopen()은 널포인터를 리턴합니다. 그리고 "input_file"이라는 이름의 파일이 존재하지 않기 때문에 input 포인터에는 Null포인터가 저장되게 됩니다. 이후 fgets()가 Null포인터에 접근해 읽으려 했기 때문에 세그멘테이션 오류를 출력하고 프로그램이 강제로 종료된 것입니다.

    위의 문제 때문에 저는 fopen()을 사용할때 보통 아래와 같이 사용합니다.

    FILE * f; f= fopen("filename.txt", "r"); if(f == Null) { printf("can`t read file\n") exit(-1); }

    추가: 위의 내용을 고쳐도 질문자님의 프로그램은 약간의 수정이 더 필요할것 같네요. 그래도 거의 다 완성된것 같으니 조금만 더 힘을 내세요 ^ ^

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)