Thread: C++ Data files

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    2

    Question C++ Data files

    how can i open a file from a program and count the lines in the files and return the total amount of lines in the file to the program?

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Maybe not the most efficient method, but probably the easiest for text files

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    
    
    
    int main(){
    
    	std::ifstream in;
    	
    	std::string filename;
    	
    	std::cout << "Enter name of file" << std::endl;
    	
    	std::getline(std::cin,filename);//get name of file
    	
    	in.open(filename.c_str());//open it
    	
    	if(!in.is_open()){//see if open was successful
    		std::cout << "Could not open " << filename;
    		return 1;
    	}
    	
    	std::string dummy;//dummy string to hold read info
    	int n = 0;//line count
    	
    	dummy.reserve(500);//try reserve memory (not needed, but may help)
    	
    	while(!in.eof()){//while not at end of file
    		std::getline(in,dummy);//read a line into a string
    		++n;//increase count	
    	}
    		
    	std::cout << "Total line count = " << n;
    
    }

  3. #3
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    Posts
    953
    I think you have to count how many times the '\n' appeared in the text file.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  2. Storing and accessing data from and to .txt files.
    By Glauber in forum C++ Programming
    Replies: 9
    Last Post: 05-27-2008, 02:59 PM
  3. reading formatted data files
    By gL_nEwB in forum C++ Programming
    Replies: 5
    Last Post: 04-22-2006, 10:09 PM
  4. Adding files of numerical data
    By Boucho in forum C Programming
    Replies: 4
    Last Post: 02-06-2006, 05:27 PM
  5. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 10:36 AM