‎03-24-2017 01:52 PM
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!
‎03-26-2017 12:02 PM
Maybe the last end of line is replaced of file tag?
‎03-27-2017 03:21 AM
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.
‎03-28-2017 02:37 PM
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.
‎03-28-2017 03:09 PM
Thanks a lot that worked!