在C++中创建文本文件并向其写入内容?

13

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


请编辑您的帖子并添加您遇到的确切错误消息。同时,完整的代码(格式正确,包括头文件)可能会有所帮助。 - Mat
@user:FileStream 是从哪里来的?为什么要创建两个流?为什么要动态创建流?你是从 Java 转到 C++ 的程序员吗? - Björn Pollex
1
FileStream?那是.NET类,对吧?你是想用C++来做吗?还是C++/CLI? - Benjamin Lindley
那么在C++中创建文本文件的函数是什么? - user637429
@user637429:请问您想使用“普通”的C++还是C++/CLI(.NET相关)? - Matteo Italia
3个回答

15
你会收到错误提示,因为你以两种不同的方式声明了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管理)指针不受垃圾回收的影响。


3
可以且应该(只在栈上)分配。 - Benjamin Lindley

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

然而,我不会为fstream对象使用动态内存(即new语句和指针)。这是新版本:

    fstream fs(filename,ios::out|ios::binary); 
fs.write("ghgh", 4); 
fs.close();

如果你正在寻找C++CLI选项(用于托管代码),我建议使用StreamWriter而不是FileStream。StreamWriter将允许您使用托管字符串。请注意,“delete”将调用IDisposable接口上的Dispose方法,并且垃圾收集器最终会释放内存:
StreamWriter ^fs = gcnew StreamWriter(gcnew String(filename));
fs->Write((gcnew String("ghgh")));
fs->Close();
delete fs;

-5

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


1
这个问题显然是关于 .txt 文件,而不是短信。这个答案中没有任何与文本文件或 Visual C++ 2008 相关的内容。 - Tyler Eich
1
@Amad Munir,你在发布那个答案时在想什么? - user4604440

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接