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
File Input and Output in C 1) Create a variable to represent the file. 2) Open the file and store this "file" with the file variable. 3) Use the fprintf or fscanf functions to write/read from the file.
You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.
Text files in C are straightforward and easy to understand. All text file functions and types in C come from the stdio library. Enter this code and run it. It waits for input from stdin, so type a few lines.
Here are examples for both native and managed C++:
Assuming you are happy with a native solution the following works just fine:
fstream *fs =new fstream(filename,ios::out|ios::binary);
fs->write("ghgh", 4);
fs->close();
delete fs; // Need delete fs to avoid memory leak
However, I would not use dynamic memory for the fstream object (i.e. the new statement and points). Here is the new version:
fstream fs(filename,ios::out|ios::binary);
fs.write("ghgh", 4);
fs.close();
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:
StreamWriter ^fs = gcnew StreamWriter(gcnew String(filename));
fs->Write((gcnew String("ghgh")));
fs->Close();
delete fs;
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:
#include <fstream>
#include <iostream>
// ...
int main()
{
// notice that IIRC on modern Windows machines if you aren't admin
// you can't write in the root directory of the system drive;
// you should instead write e.g. in the current directory
std::ofstream fs("c:\\k.txt");
if(!fs)
{
std::cerr<<"Cannot open the output file."<<std::endl;
return 1;
}
fs<<"ghgh";
fs.close();
return 0;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With