Thread: How do I specify a directory with ifstream and ofstream?

  1. #1
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Question How do I specify a directory with ifstream and ofstream?

    Hi all.
    I am trying to write code that will write and read from a file in a different directory than the current directory, but its not going so good. Here is my most recent attempt (platform is Ubuntu Linux):

    Code:
    #include <iostream>
    #include <string>
    #include <cstdio>
    #include <cstdlib>
    #include <fstream>
    
    using namespace std;
    
    void writeToFile();
    void readFromFile();
    
    void writeToFile() {
    
        ofstream out("Files/test.txt");
        if (!out) {
          cerr<< "Failed to open file. Exiting out...";
          exit(0); //failed to open file
        }
        out<< "Line 1: Rock the boat.\n"
           << "Line 2: Rock the boat.\n"
           << "Line 3: Capasize the boat.\n"
           << "Line 4: ...and finally throw someone FROM the boat. YEA!!!"<<endl;
        out.close();
    }
    
    char buf[100];
    
    const int NUMBER_OF_LINES = 4;
    int i = 0;
    void readFromFile() {
    
        ifstream in("Files/test.txt");
        if (!in) {
          cerr<< "Failed to open file. Exiting out...";
          exit(0); //failed to open file
        }
        while (i < NUMBER_OF_LINES) {
            in.getline(buf, 60);
            cout<<buf;
            cout<<'\n';
    
            i++;
        }
        in.close();
    }
    
    int main() {
    
        cout<< "This program will create a file if it doesn't already exist,\n"
            << "write some stuff to it, close the file, open it up again,\n"
            << "read from it, display its contents, and finally close the file again.\n\n"
            << "Press Enter to do this."<<endl;
    
        cin.get();
        writeToFile();
        readFromFile();
    
        return 0;
    
    }
    
    }
    Trouble is, what ends up happening is the file gets created in the current directory, instead of in the /Files directory like intended, and not only that, the file name ends up being "Files est.txt" instead of "test.txt" like I wanted to have it.

    Obviously, I don't understand how to specify a directory correctly in either an ifstream of ofstream.

    Please help.

    Thanks in advance.
    Last edited by Programmer_P; 12-04-2009 at 10:26 AM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Use a forward slash instead of a backslash. If you do want an actual backslash in a string literal, you need to escape it with another backslash.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by laserlight View Post
    Use a forward slash instead of a backslash. If you do want an actual backslash in a string literal, you need to escape it with another backslash.
    Well, I tried that too, but then it just created a file in the current directory called "Files/test.txt".

    EDIT: No wait...that actually worked. I thought I tried that before, and it didn't work, but maybe not...

    Thanks!

  4. #4
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Question

    And along these same lines, is there a way to open a directory with say ifstream, move through it with a loop, assigning the names of each file in the directory to say an element in a char array, and then display the contents of the array (i.e. the filenames of all the files in the said directory)?

    What would be the code for this?

    Could I do something like this:

    Code:
    const int FILES_IN_DIRECTORY;
    char FILENAMES[100];
    int i = 0;
    
    void readFromDirectory() {
    
        ifstream in("/Files");
        if (!in) {
          cerr<< "Failed to open directory. Exiting out...";
          exit(0);
        }
        while (i < FILES_IN_DIRECTORY) {
           //Find all files in directory and assign their names to elements in array
        }
        in.close();
    }

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Programmer_P
    And along these same lines, is there a way to open a directory with say ifstream, move through it with a loop, assigning the names of each file in the directory to say an element in a char array, and then display the contents of the array (i.e. the filenames of all the files in the said directory)?
    Yes, but not with the standard library. You could consider the use of Boost.Filesystem.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Well, here's how to do it in Win 32:

    View files in a directory - C++ - Source Code | DreamInCode.net

    But I'd prefer code that's not OS-specific.

  7. #7
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by laserlight View Post
    Yes, but not with the standard library. You could consider the use of Boost.Filesystem.
    Hmm, interesting...

    In this code, why do they have "itr" using the operator "->" instead of ".", seeing as its not a pointer?
    Code:
    bool find_file( const path & dir_path,         // in this directory,
                    const std::string & file_name, // search for this name,
                    path & path_found )            // placing path here if found
    {
      if ( !exists( dir_path ) ) return false;
      directory_iterator end_itr; // default construction yields past-the-end
      for ( directory_iterator itr( dir_path );
            itr != end_itr;
            ++itr )
      {
        if ( is_directory(itr->status()) )
        {
          if ( find_file( itr->path(), file_name, path_found ) ) return true;
        }
        else if ( itr->leaf() == file_name ) // see below
        {
          path_found = itr->path();
          return true;
        }
      }
      return false;
    }

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Programmer_P
    In this code, why do they have "itr" using the operator "->" instead of ".", seeing as its not a pointer?
    It is an iterator. Iterators generalise the concept of pointers.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Ok, so how would I access a parent directory?

    Say I had a directory structure like this:

    ~/Documents/Programming_Projects/Programming_Exercises

    and my "Programming_Exercises" executable program was located in the "Programming_Exercises" directory. In the code of the P_E program, I want to go back one directory, i.e. so that I can write and read from a file inside the "Programming_Projects" directory.

    How would I do this?

  10. #10
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Programmer_P View Post
    Ok, so how would I access a parent directory?

    Say I had a directory structure like this:

    ~/Documents/Programming_Projects/Programming_Exercises

    and my "Programming_Exercises" executable program was located in the "Programming_Exercises" directory. In the code of the P_E program, I want to go back one directory, i.e. so that I can write and read from a file inside the "Programming_Projects" directory.

    How would I do this?
    ".."
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  11. #11
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by brewbuck View Post
    ".."
    Ok...
    And if I wanted to go back one more directory, would I do:

    Code:
    ofstream out("Documents/../test.txt");
    EDIT: Nevermind. I figured it out. Its
    Code:
    ofstream out("../../test.txt");
    Should have guessed that first...
    Last edited by Programmer_P; 12-04-2009 at 12:59 PM.

  12. #12
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    But what if I went back as far as the username directory (~/):

    Code:
    ofstream out("../../../test.txt");
    and then wanted to enter a different directory in my username folder than Documents?
    Say, Pictures?
    How would I do that?

    EDIT:

    Haha...
    Guessed that one too. Its:
    Code:
    ofstream out("../../../Pictures/test.txt");

  13. #13
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    And while we're going there, is there a way to avoid hard-coding file paths?

  14. #14
    Registered User
    Join Date
    Sep 2008
    Posts
    48
    Maybe fstream is not the proper tool for your needs. The Windows API should make things easier.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Programmer_P
    And while we're going there, is there a way to avoid hard-coding file paths?
    Use a variable?

    Quote Originally Posted by like_no_other
    Maybe fstream is not the proper tool for your needs. The Windows API should make things easier.
    The Windows API is OS specific.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ofstream... broke as a result of ifstream fix
    By tms43 in forum C++ Programming
    Replies: 3
    Last Post: 11-12-2006, 11:40 AM
  2. ofstream and ifstream for searching and writing
    By johnnyd in forum C++ Programming
    Replies: 6
    Last Post: 03-17-2003, 08:34 AM
  3. ofstream, ifstream?
    By Kavity in forum C++ Programming
    Replies: 3
    Last Post: 01-20-2003, 09:49 PM
  4. Replies: 9
    Last Post: 06-06-2002, 07:03 PM
  5. STL to: Cin, Cout, ifstream & ofstream
    By kuphryn in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2001, 09:32 AM