创建一个文本文件并用C ++写入? [英] Create a text file and write to it in C++?

查看:484
本文介绍了创建一个文本文件并用C ++写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Visual C ++2008.我想创建一个文本文件并将其写入.

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();

这里显示的是FileStream错误

Here is showing error of FileStream

推荐答案

您会收到一条错误消息,因为您已经用两种不同的方式两次声明了fs.但是我不会保留任何代码,因为它是C ++和C ++/CLI的奇怪组合.

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.

在您的问题中不清楚是要执行标准C ++还是C ++/CLI;假设您要使用普通" C ++,则应该这样做:

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;
}

请注意,我删除了所有new内容,因为通常在C ++中不需要它-您可以在堆栈上分配流对象,而不必担心代码中存在的内存泄漏,因为正常(非GC管理的)指针不会进行垃圾回收.

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.

这篇关于创建一个文本文件并用C ++写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆