Hi,
I have a question about file i/o in C, just with text files not binary. How can I count the number of lines in the file pointed to by a FILE pointer?
Thanks.
Printable View
Hi,
I have a question about file i/o in C, just with text files not binary. How can I count the number of lines in the file pointed to by a FILE pointer?
Thanks.
Read entire file and count how many '\n' there are.
or if you're reading the file anyway, and have a while loop for your getline function, just declare an int before the loop and use something like
at the end of your read loop you'll also have the number of lines stored in file_lines. Regular expressions are quite useful for such tasks.Code:int file_lines=0;
while(myfile != eof){
myfile.getline(your crap here);
file_lines++;
}
If you're using a FILE pointer, you can do the same technique RandomPerson said, except with the C file functions:
The one problem with this approach is that if a line has more than 1024 characters on it, you'll get an incorrect number of lines.Code:FILE * myFile = fopen("...", "r");
int file_lines=0;
char buffer[1024];
while ( !feof(myFile) ){
fgets(myFile, 1024, myFile);
file_lines++;
}
If you are on a linux/unix machine
you could use the wc function with the -l option for the number of lines
Works for me.Code:char mystring[20];
system("wc FileName -l > xyz"); //output the contents of the wc command to a file
char delim=' ';
ifstream fileHandler;
fileHandler.open("xyz"); // opens the file
fileHandler.getline(mystring,20,delim); //reads the first word of the file
fileHandler.close();
int NumOfLines=atoi(mystring);
system("rm xyz");