I am using Visual C++ 2008. I want to create a text file and write to it.
char filename[]="C:/k.txt";
FileStream *fs = new FileStream(filename, FileMode::Create, FileAccess::Write);
fstream *fs =new fstream(filename,ios::out|ios::binary);
fs->write("ghgh", 4);
fs->close();
Here is showing error of FileStream
you create a text. Ask the user if he would like to send it. If he says yes, this means that this particular message should be tagged as outbox message otherwise it should be an inbox message.
You get an error because you have
fs
declared twice in two different ways; but I wouldn't keep anything of that code, since it's a strange mix of C++ and C++/CLI.In your question is not clear whether you want to do standard C++ or C++/CLI; assuming you want "normal" C++, you should do:
Notice that I removed all the
new
stuff since very often you don't need it in C++ - you can just allocate the stream object on the stack and forget about the memory leaks that were present in your code, since normal (non GC-managed) pointers aren't subjected to garbage collection.Here are examples for both native and managed C++:
Assuming you are happy with a native solution the following works just fine:
However, I would not use dynamic memory for the fstream object (i.e. the new statement and points). Here is the new version:
EDIT, the question was edited to request a native solution (originally it was unclear), but I will leave this answer as it may be of use to someone
If you are looking for a C++CLI option (for managed code), I recommend using StreamWriter instead of FileStream. StreamWriter will allow you work with Managed Strings. Note that delete will call the Dispose method on the IDisposable interface and the Garbage Collected will release the memory eventually: