Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ file i/o

  1. Apr 18, 2012 #1
    I felt like learning a bit about file input and output in C++. Tried some code, couldn't get it to work unless I made the path to the file a string literal, not a variable type. Why is this, and is there any way to get a string data type to be inputted as a path?
     
  2. jcsd
  3. Apr 18, 2012 #2

    Mark44

    Staff: Mentor

    You should be able to do it with the path stored in a variable. Show us the code you're talking about.
     
  4. Apr 18, 2012 #3

    I like Serena

    User Avatar
    Homework Helper

    I'm assuming you tried something like:
    Code (Text):
    std::string filename("/path/to/file");
    std::ifstream ifs(filename);
    Did you?

    If so, try:
    Code (Text):
    std::string filename("/path/to/file");
    std::ifstream ifs(filename.c_str());
     
  5. Apr 18, 2012 #4
    I tried

    Code (Text):
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;

    int main()
    {
        string file = "Documents/Programming/C++.txt";
        string contents;
        ifstream in;
        ofstream out;
        out.open(file);
        out << "This is a C++ program here." << endl;
        out.close();
        in.open(file);
        getline(in,contents);
        in.close();
        cout << contents << endl;
        return 0;
        }
    Note that I'm on a MAC, so that is a valid path. Using file.c_str seemed to work, thanks!
     
  6. Apr 18, 2012 #5

    I like Serena

    User Avatar
    Homework Helper

    You're welcome. :smile:
     
  7. Apr 18, 2012 #6

    jtbell

    User Avatar

    Staff: Mentor

    You'd think that the C++ ifstream constructor could take a C++ string as its argument. My understanding is that it's a backward-compatibility issue with ancient versions of C++ that pre-date the first standardized version (in which the 'string' data type was introduced).
     
  8. Apr 18, 2012 #7

    jhae2.718

    User Avatar
    Gold Member

    You'd still think you could create another constructor that takes a string object; I don't see how any backwards compatibility issues would occur.
     
  9. Apr 19, 2012 #8

    I like Serena

    User Avatar
    Homework Helper

    Agreed.

    You'd think they would have fixed this in C++03, but they didn't.
    I wonder why, since they must have discussed this.

    Anyway, apparently it is finally fixed in C++11.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C++ file i/o
  1. C++ Simple File I/O (Replies: 12)

  2. C file I/O (Replies: 3)

  3. FILE I/O in an IDE (Replies: 1)

Loading...