【问题标题】:Create a text file using TFileStream使用 TFileStream 创建文本文件
【发布时间】:2020-06-13 05:48:10
【问题描述】:

我尝试了以下文档中的代码:

Reading a String and Writing It To a File

但是不行,报编译错误:

“System::AnsiStringT”中没有名为“fmCreate”的成员

这是我试过的代码:

TFileStream *fs; const AnsiString str = "Hello";
fs = new TFileStream("temp.txt", fmCreate);
fs->Write ((void*)str.c_str(), str.fmCreate);

【问题讨论】:

  • 有趣的是,您链接到的是非常旧的文档,但 latest version 有相同的错字!

标签: c++ c++builder vcl tfilestream


【解决方案1】:

嗯,它只是看起来像一个错字。显然,代码正在尝试将字符串写入文件,因此需要字符串的长度。试试这个

TFileStream *fs; const AnsiString str = "Hello";
fs = new TFileStream("temp.txt", fmCreate);
fs->Write ((void*)str.c_str(), str.Length());

注意,我对 VCL 一无所知。

【讨论】:

  • 这是修正错字的正确方法。此外,不需要void* 类型转换,因为Write() 采用const void* 并且来自c_str()const char* 可以隐式转换为const void*,例如:fs->Write (str.c_str(), str.Length()); 虽然,我建议使用WriteBuffer() 而不是,如果它无法写出整个字符串,则会抛出异常,例如:fs->WriteBuffer (str.c_str(), str.Length());
【解决方案2】:

正如约翰的回答所述,文档中有错字。 str.fmCreate 应该改为 str.Length()

但是,有更好的方法可以将字符串写入文本文件以避免此问题。例如,改用System::Classes::TStreamWriterSystem::Ioutils::TFile,例如:

#include <System.Classes.hpp>

const String str = _D("Hello");
TStreamWriter *sw = new TStreamWriter(_D("temp.txt"), false, TEncoding::UTF8);
sw->Write (str);
delete sw;
#include <System.IOUtils.hpp>

const String str = _D("Hello");
TFile::WriteAllText(_D("temp.txt"), str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    相关资源
    最近更新 更多