Thread: Reading from a file

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

    Reading from a file

    How do I read a file and set the text in it to a char array?

  2. #2

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Hmm, I wouldn't recommend using that series of tutorials, they're in serious need of revision. They aren't even legal C++ anymore (they use the pre-1998 standard headers, etc.)

    Describe more how you want to read the file in -- do you want to read the entire file, all at once, into a variable, do you want to read it line by line, is it a text file or a binary file, etc.?

  4. #4
    Registered User
    Join Date
    Jun 2002
    Posts
    230
    http://www.maththinking.com/boat/computerbooks.html

    use this website and go under languages to view some c++ books. they will help you understand streams and files
    C++ Rules!!!!
    ------------
    Microsoft Visual Studio .NET Enterprise

  5. #5
    Registered User
    Join Date
    Nov 2002
    Posts
    48
    text files. I want to put the entire file into an array, and how to get the lines one by one.

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Whitespace included? So if you had:

    hello[space][space][space]there, you would want all 3 spaces between the words, just one space beween the words, or you don't care?

  7. #7
    Registered User
    Join Date
    Nov 2002
    Posts
    48
    I'd rather get exactly whats in the file, but if it's easier the other way it doesn't matter.

  8. #8
    Seeking motivation... endo's Avatar
    Join Date
    May 2002
    Posts
    537
    A quick example, apologies if there are mistakes - I havent written much C++ lately and am trying to get back into it

    Code:
    const int LINE_LENGTH = 80;
    const int LINES_TO_BE_READ = 10;
    
    int main( )
    {
       string array[ LINELENGTH ];
       ifstream fin( "test.txt", ios::in );
    
       int i;
       for( i = 0; i < LINES_TO_BE_READ; i++ )
       {
          fin >> array[ i ];
       }
       return 0;
    }
    Couldn't think of anything interesting, cool or funny - sorry.

  9. #9
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    1 sec, there's a perfect solution for you. You will probably want to download the Boost library (www.boost.org) to get its string tokenizer classes (makes the program simpler; not strictly necessary but otherwise you'll have to search for line breaks yourself). One more question: If you're going through, line by line, do you want to know when blank lines happen, or would you rather only get each non-blank line?

    Here's the easy way to read it in:

    Code:
    #include <string>
    #include <fstream>
    
        std::ifstream inputFile("c:/somedata.txt");
        std::string file((std::istreambuf_iterator<char>(inputFile)),
                          std::istreambuf_iterator<char>());
    Last edited by Cat; 06-14-2003 at 11:23 AM.

  10. #10
    Registered User
    Join Date
    Nov 2002
    Posts
    48
    One more question: If you're going through, line by line, do you want to know when blank lines happen, or would you rather only get each non-blank line?
    I'd wanna know about the blank lines.

  11. #11
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    This is what you need, then. I used the Boost library for string tokenizing; it's a very handy library to install no matter what (www.boost.org).

    Code:
    #include <fstream>
    #include <string>
    #include <boost/tokenizer.hpp>
    
        std::ifstream inputFile("c:/somedata.txt");
        std::string file((std::istreambuf_iterator<char>(inputFile)),
                          std::istreambuf_iterator<char>());
        inputFile.close();
        boost::char_separator<char> sep("\n","",boost::keep_empty_tokens);  // separate at newlines
        typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
        tokenizer tokens(file,sep);
        for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter){
            std::cout << "<" << *tok_iter << "> ";
        }
    This just prints each token; during the for loop, *tok_iter is a string which has the current line. This keeps all whitespace and empty lines are kept (they're the null string "").

    If you're using unicode files, just change string to wstring, char to wchar_t, and you should be fine.

    Oh, and the extra parentheses around the first parameter of the construction of std::string file ARE needed. It's necessary to parse correctly.

    There are many, many ways to accomplish this. I like this because it doesn't rely on arrays at all; buffer overrun is not an issue. You need to know nothing at all about the line length or line count of the file. There are no dangers of leaking resources; we never directly use arrays or pointers, and we never directly allocate memory dynamically.

    The drawback is the need of a third-party library to accomplish this.
    Last edited by Cat; 06-14-2003 at 01:43 PM.

  12. #12
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Here's an alternate solution which may be even better; it works because you're tokenizing at newlines, which is already an easy thing to do. This needs no other libraries:

    Code:
    #include <fstream>
    #include <string>
    
    
        std::ifstream inputFile("c:/somedata.txt");
        std::vector<std::string> file;
        std::string line;
        while(std::getline(inputFile,line))
            file.push_back(line);
        inputFile.close();
        for (std::vector<std::string>::iterator i = file.begin(); i != file.end(); ++i){
            std::cout << "<" << *i << "> ";
        }
    This essentially creates a vector of strings, where each string is a line. This has the advantage of easily finding numbered lines (e.g. file[12] will give the 13th line of the file). It has less power in that it can't separate the file into tokens based on arbitrary delimiters (like the first code would), and you also don't have one string that contains the entirety of the file, but if you don't need these, the above code is certainly doable.

    It has the same advantages -- no possibility of buffer overrun, no worries about dynamic memory allocation, no arrays, no memory we need to explicitly release.
    Last edited by Cat; 06-14-2003 at 01:46 PM.

  13. #13
    Registered User
    Join Date
    Nov 2002
    Posts
    48
    I tried using the secound one but I couldnt get it to work, what else do I need to add to it?

  14. #14
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Nothing; that should compile and run under any ANSI C++ compiler. What compiler(s) have you tried using it under? What errors do you get?
    Last edited by Cat; 06-15-2003 at 10:00 AM.

  15. #15
    Registered User
    Join Date
    Nov 2002
    Posts
    48
    I'm using Dev-C++, the following code gave these errors:
    `::vector' undeclared (first use here) (line 9)

    parse error before `>' (line 9)

    `file' undeclared (first use this function) (line 12)

    (Each undeclared identifier is reported only once (line 12)
    for each function it appears in.) (line 12)

    confused by earlier errors, bailing out (line 14)


    Code:
    #include <iostream.h>
    #include <fstream>
    #include <string>
    
    int main() {
    
    
        std::ifstream inputFile("text.txt");
        std::vector<std::string> file;
        std::string line;
        while(std::getline(inputFile,line))
            file.push_back(line);
        inputFile.close();
        for (std::vector<std::string>::iterator i = file.begin(); i != file.end(); ++i){
            std::cout << "<" << *i << "> ";
        }
    
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM