C언어 txt파일 읽어오기 중 세그멘테이션 오류

woodydrake의 이미지

현재 텍스트 파일에 엄청많은 숫자를 읽어와서 그숫자를 연결리스트에 집어넣는 프로그램을 만드는 도중에
작은 단계로 일단 텍스트 파일에서 숫자를 읽어오는 실험을 하고 있습니다.
아래 코드 처럼 일단 텍스트를 라인단위로 읽어와서 읽어온 데이터를 정수형으로 바꾸어 출력까지
(출력부분을 연결리스트 만드는 부분으로 바꿀예정)
진행 하였는데요

#include<stdio.h>
 
int main(int argc, char* argv[]) {
   FILE *pFile = NULL;
 
   pFile = fopen( argv[1], "r");
   if( pFile != NULL ) {
      char strTemp[255];
      char *pStr;
      int tmp;
 
      while( !feof( pFile )) {
         pStr = fgets( strTemp, sizeof(strTemp), pFile);
         tmp = atoi(pStr);
 
         printf("%d\n", tmp);
      }
      fclose(pFile);
   }
   else {
      printf("error\n");
      return 0;
   }
   return 0;
}

test.txt {
1
2
3
4
5
6
7
8
9
10

}
로 작성하고 실행하면

]$ ./pr1 test.txt
1
2
3
4
5
6
7
8
9
10
0
세그멘테이션 오류
]$

로 출력이 됩니다. 아직 프로그래밍 초보인데 while( !feof( pFile )) {
이 부분으로 제어를 하면 fclose(pFile); 로 넘어가고 프로그램끝나서 아무문제 없다고 생각했는데
어떤부분에서 세그멘테이션 오류가 나는것인지 알수 있을까요??

초보 살려주세요 ㅠㅠ~

익명 사용자의 이미지

fgets()가 NuLL을 리턴하는것을 확인해보세요.

#include<stdio.h>
 
int main(int argc, char* argv[]) {
      ....
 
      while( !feof( pFile )) {
         pStr = fgets( strTemp, sizeof(strTemp), pFile);
         if (pStr) {
             tmp = atoi(pStr);
         }
         ....
      }
   ....
   return 0;
}
twinwings의 이미지

GDB를 이용해 보세요.

어떤 라인에서 어떤 이유로 세그폴트 일어나는지 알 수 있습니다.

bushi의 이미지

feof() 는 이전 operation 의 결과가 fail 일 때 error 인지 아니면 end-of-file 인지를 알아내기 위해 사용합니다.
end-of-file 로 fail 이 된 경우 errno 가 바뀌지 않습니다.

  while (1) {
     pStr = fgets(strTemp, sizeof(strTemp), pFile);
     if (!pstr) {
        if (!feof(pFile))
            perror("fgets()");
        break;
     }
     tmp = atoi(pStr);
     ...
     ...
  }

+

"이전 operation" 은 read 와 write 를 말한 겁니다.
seek 는 해당되지 않습니다. 파일 끝을 넘어 우주 저 멀리로 포인터를 보내버려도 EOF indicator 를 변경하진 않습니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.