LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Counting the number of lines in a file?

Hello everyone,

 

I'm writing a program that reads and imports data from a CSV file. I was trying to count the number of lines in the file, so I wrote the code below. It works, however the output says there is one more line. For instance, I know the file contains 297 lines, yet it gives me 298. Here is a sample of my code:

 

int file;
ssize_t size;
int info;
char *data;
int get_data;
int count=0;
int i;

file = OpenFile (fname, VAL_READ_ONLY, VAL_OPEN_AS_IS, VAL_ASCII);
info=GetFileInfo (fname,&size);

data=(char*)malloc(size*sizeof(char));

get_data=ReadFile (file, data, size);

for(i=0;i<size;++i)
{
    if(data[i]=='\n')
{
    count=count+1;
  }
}

 

Any help would be very much appreciated!

 

Thanks!

0 Kudos
Message 1 of 5
(3,384 Views)

Maybe the last end of line is replaced of file tag?

Message 2 of 5
(3,332 Views)

I use the file utilities. I run a do while and look for EOF(End Of File)  character, counting rows based on CRLF as a row separator.

Jattie van der Linde
Engineering Manager, Software & Automation
TEL Magnetic Solutions Ltd
Message 3 of 5
(3,317 Views)

When counting lines in a file, unless you want to first determine the maximum line length in the file, reading and evaluating characters is a good way to go.  Lines typically end on a `\n` character, but this is not guaranteed.  So the best way is to count the number of times there is a non `\n` written after each '\n' that you find. 

There is a good discussion of this in detail here.

Message 4 of 5
(3,299 Views)

Thanks a lot that worked!

0 Kudos
Message 5 of 5
(3,296 Views)