2016-11-21 60 views
-3

我创建一个文件机智指定名称通过fstream的文件:函数写在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); 

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

有人可以提出一个解决方案,以显示我不明白该怎么办?

+2

*您是如何尝试“将fstream添加到函数的输入”?你能告诉我们吗?你有什么问题?如果你还没有这样做,请[阅读关于如何提出好问题](http://stackoverflow.com/help/how-to-ask)。 –

+0

@Someprogrammerdude修改我的问题以解决您提到的缺点。感谢您指出。希望现在这些都是排序的。 –

回答

1

你说的函数声明为

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 

在一个不相关的音符,使之与其他流更兼容的,我建议你使用基类std::ostream代替:

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

现在你可以通过任何种类的输出流(文件,字符串,std::cout),它会工作。

0

我不能添加评论(声誉...),为了公平起见,我不太明白你想要什么,以及你有什么问题,所以只需对你的代码发表几点评论分享(希望这有助于一点为好):

1)

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

(编译器会照顾这个反正,但仍然)

2)这里有一个错字: specifyNaneOfFile 我想这应该是 指定N ameOfFile

3)在你的函数的签名:

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

'结果' 不采取参考。我想你想要这个给调用者一些信息,如果写入成功(为什么不bool WriteToFile?)。这样,不管你在函数中设置了“结果”,它只会影响你的函数,调用者将得到它给出的结果。 即: 假设这是你的函数:

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

的主叫用户呼叫这样的:

unsigned char writeResult = 0; 
WriteToFile(writeResult) 

if (writeResult == 1) ... 

写结果将保持0

如果你想让它发生变化,通作为参考,如下:

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

另外,使用'cons t'表示你不想改变的每个参数。

+0

感谢您的意见。我会考虑他们的。请注意,我更新了我的问题,并希望您能更好地理解并解决我的问题。 –

+0

检查@Some程序员哥们的答案在我的下面。对于更新后的问题,我只会这么说。 :) –