c - How to calculate number of lines in file? -


i work in c-language @ first time , have question.

how can number of lines in file?

file *in; char c; int lines = 1; ... while (fscanf(in,"%c",&c)  == 1) {   if (c == '\n') {     lines++;   } } 

am right? don't know how moment , when string cross new line.

op's code functions aside maybe off-by-one issue , last line issue.

standard c library definition

a text stream ordered sequence of characters composed lines, each line consisting of 0 or more characters plus terminating new-line character. whether last line requires terminating new-line character implementation-defined. c11dr §7.21.2 2

a line ends '\n' , last line may or may not end '\n'.

if using idea last line of file not require final '\n, goal count number of occurrences character read after '\n'.

// let use wide type // start @ 0 file may empty unsigned long long line_count = 0;  int previous = '\n'; int ch; while ((ch = fgetc(in)) != eof) {   if (previous == '\n') line_count++;   previous = ch; }  printf("line count:%llu\n", line_count); 

reading file 1 character @ time may less efficient other means, functionally meets op goal.

this answer uses (ch = fgetc(in)) != eof instead of fscanf(in,"%c",&c) == 1 typically ""faster", optimizing compiler, either may emit similar performance code. such details of speed can supported analysis or profiling. when in doubt, code clarity.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -