파일을 읽어서 출력 할 때...

사랑천사의 이미지

int main (int argc, char **argv)
{
  /* int파트 */
  unsigned long int line;
  unsigned long int c;
  unsigned long int c2;
  int linenum = 0; /* 라인번호 출력 여부 결정 */
  unsigned long int file_size;
 
  /* char파트 */
  char fn [100];
  char *data;
  char **text;
  char *buff2;
  char key;
 
  /* FILE파트 */
  FILE *fd;
 
  if (argc == 2 && strcmp (argv[1], "-h") == 0) {
    help ();
    exit (0);
  }
  if (argc == 2 && strcmp (argv[1], "-l") == 0) {
    linenum=1;
  }
  printf ("파일명을 입력하여 주십시요.\n"
	"파일명:");
  gets (fn);
  if (strlen (fn) == 0) {
    puts ("파일명이 입력되지 않았습니다.");
    puts ("프로그램을 종료합니다.");
    exit (0);
  }
  fd = fopen (fn, "rt");
  if (fd == NULL) {
    printf ("파일을 열 수 없습니다. - %s\n", fn);
    gets ("");
    exit (1);
  }
  printf ("읽어 오는 중... - %s\n", fn);
  c = 0;
  do {
    if (feof (fd)) {
      puts ("파일 읽기에 성공.");
      *data += '\0';
      break;
    }
    key = fgetc (fd);
    *data += key;
    c++;
  } while (1);
  file_size = c - 1;
  puts ("file_size <== c");
  c = 0;
  puts ("c = 0");
  c2 = 0;
  puts ("c2 = 0");
  strcpy (buff2, data);
  puts ("복사 성공."); 
  printf ("File-Size:%ld, File-Name:%s\n", file_size, fn);
  printf ("%s\n", *buff2);
  while (1) {
    if (c >= file_size) break;
    while (c <= file_size) {
      if (text[c2][geshifilter-c] == &#039;\n&#039;) break;&#10;      text[c2] += data[c];&#10;      printf (&quot;%ld\n&quot;, c);&#10;      c++;&#10;    }&#10;    c2++;&#10;  }&#10;  line = c2;&#10;  c = 0; c2 = 0;&#10;  if (linenum == 1) {&#10;    while (c &lt;= line) {&#10;      printf (&quot;%-3d:%s\n&quot;, c + 1, text[c]);&#10;      c++;&#10;    }&#10;  }&#10;  else {&#10;    while (c &lt;= line) {&#10;      printf (&quot;%s\n&quot;, text[c]);&#10;      c++;&#10;    }&#10;  }&#10;  fclose (fd);&#10;  gets (&quot;&quot;);&#10;}&#10;&#10;  if (linenum == 1) {&#10;    while (c &lt;= line) {&#10;      printf (&quot;%-3d:%s\n&quot;, c + 1, text[c]);&#10;      c++;&#10;    }&#10;  }&#10;  else {&#10;    while (c &lt;= line) {&#10;      printf (&quot;%s\n&quot;, text[c]);&#10;      c++;&#10;    }&#10;  }&#10;  fclose (fd);&#10;  gets (&quot;&quot;);&#10;}&#10;
이걸 이렇게 하니.. Dev-C++에서 오류가 안 나고 컴파일을 됩니다. 그러나 실행 하면 문제가 많고요... GCC에서도 오류는 안 납니다. 근대 실행 하면 세그먼트 오류를 발생 시킵니다.(으으... 포인터 다시 하는것이...) &#10;char buff [8192 + 1]; 이런 식으로 해 놓고 파일을 쭈욱 읽어서 출력 하기는 쉽죠. 배열 대입 하면 되니까. 근대 이건 영... 그리고 저것을... int main (int argc, char **argv)&#10;{&#10;  /* int파트 */&#10;  unsigned long int line;&#10;  unsigned long int c, c2, c3;&#10;  int linenum = 0; /* 라인번호 출력 여부 결정 */&#10;  unsigned long int file_size;&#10;&#10;  /* char파트 */&#10;  char fn [100];&#10;  char *data;&#10;  char **text;&#10;  char *buff2;&#10;  char key;&#10;&#10;  /* FILE파트 */&#10;  FILE *fd;&#10;&#10;  if (argc == 2 &amp;&amp; strcmp (argv[1], &quot;-h&quot;) == 0) {&#10;    help ();&#10;    exit (0);&#10;  }&#10;  if (argc == 2 &amp;&amp; strcmp (argv[1], &quot;-l&quot;) == 0) {&#10;    linenum=1;&#10;  }&#10;  printf (&quot;파일명을 입력하여 주십시요.\n&quot;&#10;        &quot;파일명:&quot;);&#10;  gets (fn);&#10;  if (strlen (fn) == 0) {&#10;    puts (&quot;파일명이 입력되지 않았습니다.&quot;);&#10;    puts (&quot;프로그램을 종료합니다.&quot;);&#10;    exit (0);&#10;  }&#10;  fd = fopen (fn, &quot;rt&quot;);&#10;  if (fd == NULL) {&#10;    printf (&quot;파일을 열 수 없습니다. - %s\n&quot;, fn);&#10;    gets (&quot;&quot;);&#10;    exit (1);&#10;  }&#10;  printf (&quot;읽어 오는 중... - %s\n&quot;, fn);&#10;  c = 0;&#10;  do {&#10;    if (feof (fd)) {&#10;      puts (&quot;파일 읽기에 성공.&quot;);&#10;      data[c] = &#039;\0&#039;;&#10;      break;&#10;    }&#10;    key = fgetc (fd);&#10;    data[c] = key;&#10;    c++;&#10;  } while (1);&#10;  fclose (fd);&#10;  file_size = c - 1;&#10;  c = 0;&#10;  c2 = 0;&#10;  c3 = 0;&#10;  while (1) {&#10;    if (c &gt; file_size) break;&#10;    while (c &lt;= file_size) {&#10;      if (data[c] == &#039;\n&#039;) break;&#10;      text[c2][c3] = data[c];&#10;      c++;&#10;      c3++;&#10;    }&#10;    c3 = 0;&#10;    c2++;&#10;  }&#10;  line = c2;&#10;  c = 0; c2 = 0;&#10;  if (linenum == 1) {&#10;    while (c &lt;= line) {&#10;      printf (&quot;%-3d:%s\n&quot;, c + 1, text[c]);&#10;      c++;&#10;    }&#10;  }&#10;  else {&#10;    while (c &lt;= line) {&#10;      printf (&quot;%s\n&quot;, text[c]);&#10;      c++;&#10;    }&#10;  }&#10;  gets (&quot;&quot;);&#10;}&#10; 이렇게 바꾸었더니 윈도우즈에선 파일이 읽어는 집니다 정확히 내용이. 이놈을 strcpy나 strncpy로 buff2에 복사 하면 printf로 전부 출력이 되거든요. 그러나 그 다음이 안 되고요... 리눅스에서 gcc로 컴파일을 하니 정상이었습니다만 역시 세그먼트 오류가 납니다. 물론 파일을 읽는 대서 부터... 윈도우즈와 뭔가 다른 느낌...(당연히 다르겠죠.) 흐흠. 아무래도 포인터 쓰는걸 다시 배우던지 해야 될 것 같습니다 음. 아마 소스를 보시면 제 의도는 아실 겁니다 으음... 배열을 포인터로 대체 해 보겠다 뭐 이런 거죠 흐흠. 어떻게 해야 할 지 모르겠네요... 모두 행복하세요. 이여송 사도요한 드림.[/geshifilter-c]
7339989b62a014c4ce6e31b3540bc7b5f06455024f22753f6235c935e8e5의 이미지

data에 메모리를 할당하셔야 합니다. text도 마찬가지고요.
data = malloc (8192); 처럼 말이죠.
그리고 8192 바이트보다 더 읽게 되었으면 realloc을 사용하던지 해서 메모리를 늘려줘야 합니다.

사랑천사의 이미지

malloc와 free를 생각 해 봤는데요...
그렇게 하고 나서 나중에 데이터를 사용 하고 나면 포인터가 달라 질 것 같은데 그럼 free를 할때 문제가 생기지 않나요? 아래 어떤 글을 보니 그런 거 같은데요. 그럴 경우 원래 포인터의 위치를 다른 변수에 복사 해 두거나 해야 할 것 같은데 잘 모르겠군요. 예를 들면 이런 거죠.

#include <stdio.h>
 
int main (void)
{
  long int c;
  char *buff;
 
  buff = malloc (2000000 + 1);
 
  c = 0;
  while (c <= 2000000) {
    if (c == 2000000) {
      buff[geshifilter-c] = &#039;\9&#039;;&#10;      breadk;&#10;    }&#10;    buff[c] = &#039;L&#039;;&#10;    c++;&#10;  }&#10;  printf (&quot;%s\n&quot;, buff);&#10;  free (buff);&#10;}&#10;
이것은 문제가 없어 보이는데 만약 포인터 위치가 직접 변경 된다면 절대로 free를 시킬 수 없는 것으로 알고 있습니다.(그걸 확인 시켜 주는 글이 프로그래밍 Q&amp;A에도 있었습니다.) 그렇게 된다면 어떻게 해야 할까요? 말이 애메모호하네요. 저 소스... 원래 한 4년 쯤 전에 도스에서 짠 것이었는데, 그 때는 data 부분이 배열이었고 text는 없었습니다. 이걸 어떤 요청에 따라 포인터로 바꿔서 동작 하도록 많들려고 했더니 잘 안 되는 군요. char *name; 해 놓고 readline 함수로 읽을 때는(콘솔에서) 잘 되던 것이 직접 대입 하니 안 되는 군요 흐흠... 음... readline가 뭐 malloc를 해서 하는 것 같진 않은데...(아니 그런건가요? 내부 구현에 대해서 뜻어 보질 않았으니 으음.) 그럼 모두 행복하셨으면 합니다. 답변 감사 드리고요 음... 아 참.. 그리고 text 같은 경우 2차 포인터 인데 이건 어덯게 해야 할까요? 머리가 아프네요 으음... **니까 malloc로 할당 시키면 행열 식으로 해서 20x20 이런 식으로 할당이 될려나요 으음... 이여송 사도요한 드림. ---- 일어나라! 싸워라! 그리고 이겨라! 다만!!! 의미 있는 것에 그 힘을!!! 그 능력과 노력을!!![/geshifilter-c]

사람천사

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.