创建一个文本文件并用C++写入它?

use*_*429 13 c++ file-io text-files

我正在使用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();
Run Code Online (Sandbox Code Playgroud)

这是显示FileStream的错误

Mat*_*lia 14

你得到一个错误,因为你已经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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我删除了所有的new东西,因为在C++中你经常不需要它 - 你可以只在堆栈上分配流对象而忘记代码中存在的内存泄漏,因为正常(非GC管理)指针不受垃圾收集.

  • 可以*和应该*[只在堆栈上分配] (3认同)

Dav*_*vey 5

以下是本机和托管 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
Run Code Online (Sandbox Code Playgroud)

但是,我不会为 fstream 对象(即新语句和点)使用动态内存。这是新版本:

    fstream fs(filename,ios::out|ios::binary); 
fs.write("ghgh", 4); 
fs.close();
Run Code Online (Sandbox Code Playgroud)

编辑,问题被编辑以请求本地解决方案(最初不清楚),但我会留下这个答案,因为它可能对某人有用

如果您正在寻找 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;
Run Code Online (Sandbox Code Playgroud)