input/output to text file

"qbschmidt" <> wrote in message
news:...
> i can input and output to a text file as long as the file is in the
> same directory as my c++ program. but i cant figure out how to
> input/output to a file in another directory i.e. I:\c++projects
> please help.
> thanks

Advertisements

i can input and output to a text file as long as the file is in the
same directory as my c++ program. but i cant figure out how to
input/output to a file in another directory i.e. I:\c++projects
please help.
thanks

Advertisements

"lallous" <> wrote in message
news:...
> Specify the full path instead of just the file name, as:
>
> fstream f("i:\\c++projects\\yourfile.txt", ios::binary);

You can also usually also use .. as in

fstream f("..\\lib\\yourfile.txt", ios::binary);

But these types of details are outside the scope of C++, which knows nothing
about directories. Note that these directories are usually relative to: (1)
if running from the command line then the directory from which you ran the
program (which may be different from the directory the program lives in),
(2) in Windows the the Start In property which you can see when you right
click the file.

To avoid harcoding directory names you can use the the standard C function
getenv to get an environment variable by name. But this design requires the
existence of an environment variable, which comes with its own hassles,
especially in the install script. You can also require the user to specify
a config file in the command line which you can retrieve from argv. The
config file often hard codes absolute directory names.

"lallous" <> wrote in message news:<>...
> "qbschmidt" <> wrote in message
> news:...
> > i can input and output to a text file as long as the file is in the
> > same directory as my c++ program. but i cant figure out how to
> > input/output to a file in another directory i.e. I:\c++projects
> > please help.
> > thanks
>
> Hello,
>
> Specify the full path instead of just the file name, as:
>
> fstream f("i:\\c++projects\\yourfile.txt", ios::binary);

Note the presence of \\. \c is an illegal excape sequence.
"i:\temp" means "i: emp" because \t is a tab.

You can also use "i:/c++projects/yourfile.txt". This may
be surprising to users, but forward slashes work on more
systems. (not on all, though. File systems aren't standard.)

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!