0

Basically I am trying to read a "block" of data from a file that looks something like

000000000
000000001
000100000
100000000

000000000
000000000
000000000  

The above example would translate into TWO blocks of data. First one is 4 lines tall, second one is 3 lines tall.

The double spaces separates the "blocks".

Here is my code to read until double space is encountered. (This reads the first loop, I then use fseek to read whatever other block I want to read - it doesn't really matter in this question though)

while(!endofblock){
  firstchar = fgetc(fptr); //read the first character
    if(firstchar == '\n'){ 
       if(fgetc(fptr) == '\n'){ //if its newline AND newline
          endofblock = 1; //end of block is reached, loops break
       }else{  //if its just one new line
          *h = *h + 1; //increment h (height), a pointer passed from elsewhere
       }
    }

  if(feof(fptr)){ 
    endofblock = 1; 
  }
}

This works fine most of the time - but there are complex unexplainable cases that it doesn't work. Plus, it is very bloated and messy.

Is there a neater, better way to count the number of new line and stop counting when double new line is reached?

40pro
  • 1,283
  • 2
  • 15
  • 23
  • 1
    Read line by line & then split/parse the read line - much easier than reading char by char – user93353 Nov 25 '12 at 04:27
  • @stackplasm no, by using the `getline` function. – Xymostech Nov 25 '12 at 04:47
  • Keep in mind that gnu readline requires that you use gpl for your project. IMO, the main advantage with readline is the emacs editing and history that is useful for prompts, but this doesn't matter when it is used to read from a file. There is nothing wrong with fgets. – foo Nov 27 '12 at 00:57

1 Answers1

0

Use the getline function:

char *line = NULL;
size_t linecap = 0;
ssize_t linelen;

while ((linelen = getline(&line, &linecap, fp)) > 0) {
    if (line[0] == '\n') {
        // block ended
    }
}

free(line);
Xymostech
  • 9,710
  • 3
  • 34
  • 44
  • This code works. It's perfect. But I have no idea what size_t is and why the second argument of getline is the address of linecap.. – 40pro Nov 25 '12 at 05:47
  • Go look at `man getline` to answer all your questions. In short, `size_t` is just an integer whose size is that same as a pointer (so like, a `long`), and linecap is the amount of memory allocated at the `line` position. – Xymostech Nov 25 '12 at 05:52
  • also according to this website: http://www.dreamincode.net/forums/topic/146250-how-to-use-getline-in-c-programming/ : "getline doesn't exist in ANSI standard C. - fgets perhaps isn't perfect, but its probably the safest option of all the standard functions available in " ....? – 40pro Nov 25 '12 at 05:53
  • 1
    See http://stackoverflow.com/questions/5565751/status-of-posix-implementations (basically, go ahead and use it, any reasonably up-to-date compiler will support it) – Xymostech Nov 25 '12 at 05:57