在 C++ 中通过 fstream 写入文件的函数

Function to write to file via fstream in C++

我创建了一个指定名称的文件:

#include <fstream>

SYSTEMTIME systime;
GetSystemTime (&systime);

CString filename;
filename =     specifyNameOfFile(timestamp, suffix); // call a method

std::ofstream fstream(filename,     std::ios_base::app | std::ips_base::out);

我想创建一个类似

的方法
void WriteToFile(unsigned int count, WORD hour, WORD minute, unsigned char result);

void WriteToFile(unsigned int count, WORD hour, WORD minute, unsigned char result) 
{
    fstream << count << " " << hour << " " << minute << " " << result << "\n";
}

它将输入要写入文件的内容并且应该使用之前定义的fstream。

我尝试将 fstream 添加到函数的输入但没有成功:

void WriteToFile(std::ofstream fstream, unsigned int count, WORD hour, WORD minute, unsigned char result);

error C2248VC\include\fstream(803) : cannot access private member declared in class 'std::basic_ios<_Elem, _Traits>'

有人可以提出解决方案来说明我不明白该怎么做吗?

我不能添加评论(声望...),公平地说,我不太明白你想要什么,你的问题是什么,所以只是对代码的一些评论你'已分享(希望这也能有所帮助):

1)

CString filename;
filename = ...
Would be much prettier like this:
CString filename = ...

(编译器无论如何都会处理这个问题,但仍然)

2) 这里有一个错字: 指定文件名 我想这应该是 指定文件名

3) 在你的函数签名中:

void WriteToFile(unsigned int count, WORD hour, WORD minute, unsigned char result);

'result'不作参考。我想如果写入成功,您希望它向调用者提供一些信息(为什么不 bool WriteToFile?)。这样,无论您在函数中设置 'result' 什么,它只会影响您的函数,调用者将得到它所提供的。 IE。: 假设这是您的职能:

void MyClass::WriteToFile(unsigned char result)
{
result = 1;
}

来电者是这样称呼的:

unsigned char writeResult = 0;
WriteToFile(writeResult)

if (writeResult == 1) ...

writeResult 将保持为 0。

如果你想改变它,作为参考传递,就像这样:

void WriteToFile(unsigned int count, WORD hour, WORD minute, unsigned char &result);

此外,对您不打算更改的每个参数使用 'const'。

你说函数声明为

void WriteToFile(std::ofstream fstream, unsigned int count, WORD hour, WORD minute, unsigned char result);

这有一个问题,因为您尝试按值传递流,这意味着它被复制了。而且你不能复制流对象。

通过引用传递它而不是:

void WriteToFile(std::ofstream& fstream, unsigned int count, WORD hour, WORD minute, unsigned char result);
//                            ^
//                            Note ampersand here

顺便说一句,为了使其与其他流更兼容,我建议您改用基础 class std::ostream

void WriteToFile(std::ostream& ostream, unsigned int count, WORD hour, WORD minute, unsigned char result);

现在您可以传递 任何 类型的输出流(文件、字符串、std::cout)并且它会起作用。