Thread: reading a file in a different directory than where the program is located

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    205

    reading a file in a different directory than where the program is located

    Hi,
    I am currently using fstream in C++ to read files. I have noticed that only file names are passed when opening a file. I was curious if there is a way to specify a different directory. The following does not work:
    Code:
    std::ifstream in ("C:\test\node1trans.sim");
    std::cout <<in.get();
    in.get() returns -1
    thanks for the help,
    Amish

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You forgot the \\ quoting of \ in your pathname.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    '\' is an escape character in C++. In fact, '\t' is a tab and '\n' is a newline character. Try this:
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
       
        cout<<"C:\test\node1trans.sim"<<endl;
        
        system("PAUSE");
        return 0;
    }
    To get the literal character '\' you have to escape it: '\\'.

  4. #4
    Registered User
    Join Date
    Dec 2004
    Posts
    205
    Damn I cannot believe I did not catch that. Well thanks for help, it works now,
    Amish

  5. #5
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    One further note is that forward slashes works as well ie. "C:/test/node1trans.sim" to avoid the double \\

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  2. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM