fopen with std::string

This is a discussion on fopen with std::string within the C++ Programming forums, part of the General Programming Boards category; Originally Posted by Ducky Ok, thanks Tux0r for your help! I dont understand right now what you're saying but i ...

  1. #16
    C++11 User Tux0r's Avatar
    Join Date
    Nov 2008
    Location
    Sweden
    Posts
    135
    Quote Originally Posted by Ducky View Post
    Ok, thanks Tux0r for your help!
    I dont understand right now what you're saying but i will look after it later when i'll have the time.

    For now i got Laserlight and Sebastiani telling me to prefer fstream so i rewrote the program with fstream.[/CODE]
    I meant that I prefer C++ streams (like std::fstream) even with cstdio being faster...
    Speed doesn't mean it's better to use in practice.

    For example you don't have to filestr.close(); if you don't feel like so.

  2. #17
    Registered User
    Join Date
    Dec 2007
    Posts
    796
    Ah ok, i understand!

    "For example you don't have to filestr.close(); if you don't feel like so. "
    Really? Thats great! No disadvantage?

    But in my program i have to because i recall it again and again.

    Another thing. I tried to clear 'stringstream ss' with 'ss << "";' and 'ss.clear();'
    but it didnt worked.
    Then i saw that Laserlight redeclared it each time in the loop.
    So the fact that redeclaring it, it clears its content.

    Im just wondering if there is another way to do it.
    I googled but found nothing apart 'ss << "";' and 'ss.clear();' .
    Compiler MSVC++ 2013 with Code::Blocks.

  3. #18
    C++11 User Tux0r's Avatar
    Join Date
    Nov 2008
    Location
    Sweden
    Posts
    135
    Code:
    ss.str("");
    ss.clear()
    Is the way to do it, I believe.

    Quote Originally Posted by Ducky View Post
    Ah ok, i understand!
    "For example you don't have to filestr.close(); if you don't feel like so. "
    Really? Thats great! No disadvantage?
    Not really, as the object is destructed, it frees appropriate resources
    Code:
    void lol() {
        std::ifstream f("lol");
    
        f<<"lol";
    } //lol         just kidding... here "f" is closed automatically
    Last edited by Tux0r; 07-29-2009 at 06:26 AM.

  4. #19
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Basically, a C++ fstream automatically closes itself when the object is destroyed. So in your example,
    Code:
    int main ()
    {
        const string filename  = "file";
        const string extension = ".txt";
        stringstream ss;
        string word;
    
        for (int i = 0; i < 5; ++i)
        {
            cout << "Enter word: "; cin >> word;
            ss << filename << i << extension;
            fstream filestr;
            filestr.open (ss.str().c_str(), fstream::in | fstream::out | fstream::app);
            filestr << word.c_str() << endl;
        }
    
    
         return 0;
    }
    you wouldn't be able to leave out the .close(). You declare the fstream object outside the loop, and so it isn't destructed for each loop iteration. And calling .open() again doesn't automatically close the file, as this page indicates:
    If the object already has a file associated (open), the [open()] function fails.
    Your code is fine as is, but if you wanted to take advantage of automatic-filestream-closing, you could do this:
    Code:
    int main ()
    {
        fstream filestr;
        filestr.open ("test.txt", fstream::in | fstream::out | fstream::app);
    
        const string filename  = "file";
        const string extension = ".txt";
        stringstream ss;
        string word;
    
        for (int i = 0; i < 5; ++i)
        {
            cout << "Enter word: "; cin >> word;
            ss << filename << i << extension;
            filestr.open (ss.str().c_str(), fstream::in | fstream::out | fstream::app);
            filestr << word.c_str() << endl;
            filestr.close();
        }
    
    
         return 0;
    }
    Since the fstream object is declared inside the loop, it will be destructed when the loop finishes an iteration and begins the next. And it will automatically close itself when this happens. This probably isn't as efficient, execution-speed wise (allocating and freeing the fstream variable), but I doubt that it's a significant speed hit, especially since file I/O is so slow. And it means that you don't have to remember to close the file yourself.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #20
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    dwks, it appears your code examples are backwards.

  6. #21
    Registered User
    Join Date
    Dec 2007
    Posts
    796
    Thank you Dwks i was wondering how to do it indeed.

    Yes i guess the examples mixed up.
    Compiler MSVC++ 2013 with Code::Blocks.

  7. #22
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    BTW, this:
    Code:
    filestr << word.c_str() << endl;
    should be:
    Code:
    filestr << word << endl;
    The only weirdness with strings and fstreams is when providing a filename to open. The operator<< and operator>> used with the streams work fine with strings.

  8. #23
    Registered User
    Join Date
    Dec 2007
    Posts
    796
    Yes i figured that out in the meantime, thanks!

    And whats the deal with the 'fstream::in' or 'ios::in'.

    Its if i use 'fstream filestr;' i should use 'fstream::in',

    and if i use 'ofstream' or 'ifstream' i must use 'ios::in'?
    Compiler MSVC++ 2013 with Code::Blocks.

  9. #24
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by Ducky View Post
    Yes i figured that out in the meantime, thanks!

    And whats the deal with the 'fstream::in' or 'ios::in'.

    Its if i use 'fstream filestr;' i should use 'fstream::in',

    and if i use 'ofstream' or 'ifstream' i must use 'ios::in'?
    There's no difference. fstream is derived (ultimately) from ios_base, and as such you can access the flags by prefixing them with the fsteam class name. In other words, had you derived a class my_ofstream from ofstream you could access the flags as my_ofstream::in, etc.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  10. #25
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    >> and if i use 'ofstream' or 'ifstream' i must use 'ios::in'?

    Most of the time the default values are all you need, so you don't actually have to use all those flags. If you are reading from a file use an ifstream (which defaults to ios::in) and if you're writing to a file use ofstream (which defaults to ios::out). I think you would need ios::app if you're appending to the end of the output file, but otherwise you should be good without those cluttering up the code.

  11. #26
    C++11 User Tux0r's Avatar
    Join Date
    Nov 2008
    Location
    Sweden
    Posts
    135
    The only thing to really remember is to use std::ios:binary when you are doing read and write if you want code that works on Windows

  12. #27
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    >> The only thing to really remember is to use std::ios:binary when you are doing read and write if you want code that works on Windows

    That doesn't make sense and I'm pretty sure it's not true. I'm not sure why you'd think that.

  13. #28
    Registered User
    Join Date
    Dec 2007
    Posts
    796
    And if i use fstream i can do both reading and writing to a file?
    Or whats good then fstream for?

    I dont understand whats happening here, nothing's getting written to the file.

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    ofstream file;
    
    int main () {
    
        string word;
        file.open ("test.txt", ios::app);
        file << "\nOk"; 
    
        while(1){
                cout << "Enter word: "; cin >> word;
                file << word << "\n";
        }
    
      return 0;
    }
    Last edited by Ducky; 07-31-2009 at 12:50 PM.
    Compiler MSVC++ 2013 with Code::Blocks.

  14. #29
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by Ducky View Post
    And if i use fstream i can do both reading and writing to a file?
    Or whats good then fstream for?

    I dont understand whats happening here, nothing's getting written to the file.

    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    ofstream file;
    
    int main () {
    
        string word;
        file.open ("test.txt", ios::app);
        file << "\nOk"; 
    
        while(1){
                cout << "Enter word: "; cin >> word;
                file << word << "\n";
        }
    
      return 0;
    }
    File I/O is buffered, and if you kill the program (which is the only way this program is going to stop) you may or may not get that buffer written out. Write a program that actually ends, and you may get something you like.

  15. #30
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    >> And if i use fstream i can do both reading and writing to a file?

    Yes, but there are only rare occasions where you actually want to do that with the same fstream variable. Normally, you'd have two separate variables, one for reading and one for writing, since the reading and writing would happen at different points in your program. (For example, you read in your data file at the beginning, then after the user makes changes, you write it out again at the end.)

Page 2 of 3 FirstFirst 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 13
    Last Post: 12-14-2007, 02:34 PM
  2. std::string: Has my compiler gone nuts??
    By Andruu75 in forum C++ Programming
    Replies: 9
    Last Post: 09-28-2007, 04:02 AM
  3. Debugging help
    By cuddlez.ini in forum C++ Programming
    Replies: 3
    Last Post: 10-24-2004, 07:08 PM
  4. DLL and std::string woes!
    By Magos in forum C++ Programming
    Replies: 7
    Last Post: 09-08-2004, 12:34 PM
  5. returning std::string
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 09-24-2001, 08:31 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21