...

View Full Version : Creating .txt files via C++ applications...



The_Pope666
05-13-2007, 03:47 PM
Hello everybody,

I have a question regarding C++. Which commads do I use in one of my programs to create a simple .txt document (with the word "hi" or something else in it), on, let's say, the Desktop. First of all, I don't know any of the commads for doing this, and second of all, will it even be possible to create a .txt on the desktop via code? I mean, technically the desktop is located at C:\Dokumente und Einstellungen\Username\Desktop (sorry, it's german). What I mean though is, this will differ from computer to computer since everyone has a different user name. Or is there a simple way around this?

Regards,
Chris

oracleguy
05-13-2007, 05:23 PM
To write a text file in C++ you use the ofstream class. You'll need to include fstream. You write to it just like cout.

As for the desktop location, you can use the HOMEPATH enviorment variable to get there, e.g.

"%HOMEPATH%\Desktop\file.txt"

I haven't actually tried that in C++ but it hopefully will work.

The_Pope666
05-13-2007, 06:14 PM
thanks, I looked into it, and this code seems to work fine:



#include <fstream>
.
.
.
ofstream fout;
fout.open("output.txt");



The file shows up on the desktop (I didn't add the line you gave me, I will thoug), because the application is in the same directory i guess...

But how do I have text in the file as soon as it is created? Right now, it's just empty.

Regards,
Chris

oracleguy
05-13-2007, 11:15 PM
Well yes, if you don't specify a path, it just creates the folder in the whatever path the application is running in.


But how do I have text in the file as soon as it is created? Right now, it's just empty.

You can't really but once you open the file you can write to it all you want.


fout << "This text will be written into the file." << endl;

Is there a reason the file has to have text in it, the exact nanosecond the file is created?

Oh and don't forget to close the ofstream object you opened before your program ends.

ghell
05-14-2007, 12:58 AM
googled for "C++ file IO" and this came out top:
http://www.cplusplus.com/doc/tutorial/files.html

Seems to cover everything you need to me.

You can still use the C file I/O functions (fprintf etc) if you get confused by C++ streams.

The_Pope666
05-14-2007, 01:56 PM
alright that should work, thanks guys!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum