Thread: segmentation fault

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    3

    segmentation fault

    I have this function:

    Code:
    void count_airplanes(void)
    {
      char line[DIML];
      char *vn;
      FILE *f_simulation = NULL;
    
      if((f_simulation = fopen("simulation.txt", "r"))==NULL)
      {
        printf("Can't open file %s", "simulation.txt");
        return;
      }
    
    while(fgets(line, DIML, f_simulation)!= NULL)
    { 
      vn = fgets(line, DIML, f_simulation);
    
      if(vn[0] == 'A')
      {printf("%s", vn);}
    }
    What I want is to find the lines in my file that start with an "A". But for some reason this function is only finding the first line that starts with "A", and after it, the error message "segmentation fault" appears. Can someone help me please? Thanks!

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Where do you allocate any memory for the variable vn?

    Jim

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    3
    I don't know if I understood correctly your question, but the variable vn is each line of the file simulation.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Each call to fgets reads a separate line. You call it once in your while loop condition and once in the body. You actually don't even need the vn variable:
    Code:
    while (fgets(line, DIML, f_simulation) != NULL) {
        if (line[0] == 'A') {
            printf("%s", line);
        }
    }
    Your code doesn't show a call to fclose, so make sure you close your file when you're done.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    3
    Finally I did it! thanks a lot!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation Fault
    By lombardom in forum C Programming
    Replies: 8
    Last Post: 06-06-2010, 03:17 PM
  2. segmentation fault
    By kiz in forum C Programming
    Replies: 5
    Last Post: 09-23-2007, 11:00 PM
  3. Segmentation fault
    By (Slith++) in forum C++ Programming
    Replies: 4
    Last Post: 05-06-2007, 03:47 AM
  4. segmentation fault when using gcc
    By stodd04 in forum C Programming
    Replies: 6
    Last Post: 02-14-2005, 07:34 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM