string - Reading the number of entries in a data file in C -


i trying write c program reads how many lines/entries there in set data file. have used code below , works fine (gotten from: what easiest way count newlines in ascii file?)

#include <stdio.h>  int main() { file *correlations; correlations = fopen("correlations.dat","r"); int                 c;              /* nb. int (not char) eof */ unsigned long       newline_count = 0;      /* count newline characters */ while ( (c=fgetc(correlations)) != eof ) {     if ( c == '\n' )         newline_count++; }  printf("%lu newline characters\n", newline_count); return 0; } 

but wondering if there way change bit

if ( c == '\n' )         newline_count++; 

into else if data looks like

1.0  2.0  3.0  

(with entry new line space entry space) instead of

1.0 2.0 3.0 

how differentiate between character/string/integer , new line? tried %s didn't work.. trying out first on small file 3 entries, using big file later on have spaces between each line i'm wondering how differentiate... or should divide line_count 2 number of entries?

you can make flag tells you saw @ least 1 non-whitespace character after last \n, increment line counter when flag set 1:

unsigned int sawnonspace = 0; while ( (c=fgetc(correlations)) != eof ) {     if ( c == '\n' ) {         newline_count += sawnonspace;         // reset non-whitespace flag         sawnonspace = 0;     } else if (!isspace(c)) {         // next time see `\n`, we'll add `1`         sawnonspace = 1;     } } // last line may lack '\n' - add anyway newline_count += sawnonspace; 

dividing count 2 not reliable, unless guaranteed have double spacing in files.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -