Create a text file and write to it in C++?

梦想与她 提交于 2020-01-12 06:55:07

问题


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

Here is showing error of FileStream


回答1:


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.

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

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.




回答2:


Here are examples for both native and managed C++:

Assuming you are happy with a native solution the following works just fine:

    fstream *fs =new fstream(filename,ios::out|ios::binary); 
fs->write("ghgh", 4); 
fs->close(); 
delete fs;      // Need delete fs to avoid memory leak

However, I would not use dynamic memory for the fstream object (i.e. the new statement and points). Here is the new version:

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

EDIT, the question was edited to request a native solution (originally it was unclear), but I will leave this answer as it may be of use to someone

If you are looking for a C++CLI option (for managed code), I recommend using StreamWriter instead of FileStream. StreamWriter will allow you work with Managed Strings. Note that delete will call the Dispose method on the IDisposable interface and the Garbage Collected will release the memory eventually:

StreamWriter ^fs = gcnew StreamWriter(gcnew String(filename));
fs->Write((gcnew String("ghgh")));
fs->Close();
delete fs;



回答3:


you create a text. Ask the user if he would like to send it. If he says yes, this means that this particular message should be tagged as outbox message otherwise it should be an inbox message.



来源:https://stackoverflow.com/questions/5362607/create-a-text-file-and-write-to-it-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!