我正在使用Visual C ++ 2008.我想创建一个文本文件并写入它。
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();
这是显示FileStream的错误
你得到一个错误,因为你有 fs
以两种不同的方式宣布两次;但我不会保留任何代码,因为它是C ++和C ++ / CLI的奇怪组合。
在您的问题中,您不清楚是否要执行标准C ++或C ++ / CLI;假设你想要“普通”的C ++,你应该这样做:
#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;
}
请注意,我删除了所有 new
因为在C ++中你通常不需要它 - 你可以只在堆栈上分配流对象而忘记代码中存在的内存泄漏,因为正常(非GC管理的)指针不受垃圾收集。
以下是本机和托管C ++的示例:
假设您对本机解决方案感到满意,以下工作正常:
fstream *fs =new fstream(filename,ios::out|ios::binary);
fs->write("ghgh", 4);
fs->close();
delete fs; // Need delete fs to avoid memory leak
但是,我不会为fstream对象使用动态内存(即新的语句和点)。这是新版本:
fstream fs(filename,ios::out|ios::binary);
fs.write("ghgh", 4);
fs.close();
编辑,问题被编辑,以请求原生解决方案(最初不清楚),但我会留下这个答案,因为它可能对某人有用
如果您正在寻找C ++ CLI选项(对于托管代码),我建议使用StreamWriter而不是FileStream。 StreamWriter将允许您使用托管字符串。请注意,delete将在IDisposable接口上调用Dispose方法,而Garbage Collected将最终释放内存:
StreamWriter ^fs = gcnew StreamWriter(gcnew String(filename));
fs->Write((gcnew String("ghgh")));
fs->Close();
delete fs;
你创建一个文本。询问用户是否要发送它。如果他说是,这意味着该特定消息应该被标记为发件箱消息,否则它应该是收件箱消息。