Thread: anyone could look at this code for me??

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    3

    Unhappy anyone could look at this code for me??

    test.c
    Code:
    #include <stdio.h> 
    
    int main(int argc, char *argv[]) 
    { 
        char *file[256]; 
        int line = 0; 
    
        if(argc == 2) { 
            FILE *fp; 
            fp = fopen(argv[1],"r"); 
            while(fgets(file[line],81,fp) != NULL){ 
                printf("file[%d] is [%s]\n",line,file[line]); 
                line++; 
            } 
            fclose(fp); 
            return 0; 
        } else { 
            printf("ERROR\n"); 
            return 1; 
        } 
    }
    If I run it after compile,
    >./a.out result.txt
    file[0] is [2]
    file[1] is [korea]
    file[2] is [united States]
    file[3] is [3,2]
    above this is supposed to be result, but it said
    segmentation fault after print out file[0] is [2]

    result.txt is like this..
    2
    korea
    united States
    3,2

    plz ..help..me..


    &#91;code]&#91;/code]tagged by Salem

  2. #2
    Registered User
    Join Date
    Oct 2002
    Posts
    4

    Unhappy Hey man, I am having the same problem.

    Yo, I love to help u out, but I am also facing the same problem. Our code is very similar and I am sure that we are doing the same question. I will let u know when I discover the problem. Hang in there dude! Peace!

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    The problem is you want to store all lines from file in memory. Don't do that. Take one buffer and reuse this buffer for each line you read:

    Code:
    int line = 0;
    char buf[BUFSIZ];
    ...
    while(fgets(buf, BUFSIZ, fp) != NULL)
    {
       printf("line[%d] is [%s]\n", line, buf); 
       line++;
    }
    ...
    And don't forget to check the return value of fopen!

    Hope this helps.
    Last edited by Monster; 10-31-2002 at 03:28 AM.

  4. #4
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    And your result will be:
    Code:
    line[0] is [2
    ] 
    line[1] is [korea
    ] 
    line[2] is [united States
    ] 
    line[3] is [3,2
    ]
    because fgets also reads the newline character...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Extended ASCII Characters in an RTF Control
    By JustMax in forum C Programming
    Replies: 18
    Last Post: 04-03-2009, 08:20 PM
  2. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  3. Obfuscated Code Contest
    By Stack Overflow in forum Contests Board
    Replies: 51
    Last Post: 01-21-2005, 04:17 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM