|
-
March 27th, 2008, 01:20 AM
#1
How to count number of lines in a text file
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.
-
March 27th, 2008, 03:23 AM
#2
Re: How to count number of lines in a text file
Read entire file and count how many '\n' there are.
-
March 28th, 2008, 09:10 AM
#3
Re: How to count number of lines in a text file
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
Code:
int file_lines=0;
while(myfile != eof){
myfile.getline(your crap here);
file_lines++;
}
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.
-
March 28th, 2008, 10:45 AM
#4
Re: How to count number of lines in a text file
If you're using a FILE pointer, you can do the same technique RandomPerson said, except with the C file functions:
Code:
FILE * myFile = fopen("...", "r");
int file_lines=0;
char buffer[1024];
while ( !feof(myFile) ){
fgets(myFile, 1024, myFile);
file_lines++;
}
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.
-
March 29th, 2008, 01:03 AM
#5
Re: How to count number of lines in a text file
If you are on a linux/unix machine
you could use the wc function with the -l option for the number of lines
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");
Works for me.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|