What is the most elegant way to read a text file with c++?

前端 未结 5 1113
广开言路
广开言路 2020-11-28 00:49

I\'d like to read whole content of a text file to a std::string object with c++.

With Python, I can write:

text = open(\"text.txt\", \"         


        
5条回答
  •  隐瞒了意图╮
    2020-11-28 01:22

    But beware that a c++-string (or more concrete: An STL-string) is as little as a C-String capable of holding a string of arbitraty length - of course not!

    Take a look at the member max_size() which gives you the maximum number of characters a string might contain. This is an implementation definied number and may not be portable among different platforms. Visual Studio gives a value of about 4gigs for strings, others might give you only 64k and on 64Bit-platforms it might give you something really huge! It depends and of course normally you will run into a bad_alloc-exception due to memory exhaustion a long time before reaching the 4gig limit...

    BTW: max_size() is a member of other STL-containers as well! It will give you the maximum number of elements of a certain type (for which you instanciated the container) which this container will (theoretically) be able to hold.

    So, if you're reading from a file of unknow origin you should:
    - Check its size and make sure it's smaller than max_size()
    - Catch and process bad_alloc-exceptions

    And another point: Why are you keen on reading the file into a string? I would expect to further process it by incrementally parsing it or something, right? So instead of reading it into a string you might as well read it into a stringstream (which basically is just some syntactic sugar for a string) and do the processing. But then you could do the processing directly from the file as well. Because if properly programmed the stringstream could seamlessly be replaced by a filestream, i. e. by the file itself. Or by any other input stream as well, they all share the same members and operators and can thus be seamlessly interchanged!

    And for the processing itself: There's also a lot you can have automated by the compiler! E. g. let's say you want to tokenize the string. When defining a proper template the following actions:
    - Reading from a file (or a string or any other input stream)
    - Tokenizing the content
    - pushing all found tokens into an STL-container
    - sort the tokens alphabetically
    - eleminating any double values
    can all(!!) be achived in one single(!) line of C++-code (let aside the template itself and the error handling)! It's just a single call of the function std::copy()! Just google for "token iterator" and you'll get an idea of what I mean. So this appears to me to be even more "elegant" than just reading from a file...

提交回复
热议问题