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


我正在使用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的错误


11356
2018-03-19 14:11


起源

请编辑您的帖子并添加您的确切错误消息。此外,完整的代码(格式正确,带标题)可能会有所帮助。 - Mat
@user:在哪里 FileStream 来自?你为什么要创建两个流?为什么要动态创建流?你是一个转向C ++的Java程序员吗? - Björn Pollex
的FileStream?这是一个.NET类吗?你想做C ++吗?还是C ++ / CLI? - Benjamin Lindley
那么在c ++中创建文本文件的功能是什么? - user637429
@ user637429:再次,你想做“普通”的C ++或C ++ / CLI(.NET的东西)吗? - Matteo Italia


答案:


你得到一个错误,因为你有 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管理的)指针不受垃圾收集。


13
2018-03-19 14:45



能够 并且应该 [只在堆栈上分配] - Benjamin Lindley


以下是本机和托管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;

3
2018-03-19 14:48





你创建一个文本。询问用户是否要发送它。如果他说是,这意味着该特定消息应该被标记为发件箱消息,否则它应该是收件箱消息。


-4
2018-04-02 19:36



问题显然是关于 .txt 文件,而不是短信。此答案中没有任何内容涉及文本文件或Visual C ++ 2008。 - Tyler Eich
@Amad Munir在发布答案时你在想什么 - Digvijay Rathore