如何写出文件并使其返回文件

时间:2015-04-14 06:20:11

标签: c++ xcode function class file-io

int fileReading(string signalFile){
    ofstream fileName;
    fileName.open(signalFile, ios::in | ios::binary);

    //does more stuff here

fileName.close();
return 0;

}

如何创建新文件并将函数的返回类型切换为文件?

我需要为此创建一个类吗?

1 个答案:

答案 0 :(得分:0)

最容易且可能最一致的事情是让你的函数以fstream作为参数(通过引用)然后返回它,

fstream& fileReading(fstream& strm)
{
    // process it here
    return strm;
}

这样您就不会将文件名与流混合,因此您的函数只做一件事:处理流。一旦定义了函数,就可以像

一样使用它
fstream fileName("test.txt", ios::in | ios::binary); // we open the stream
fileReading(fileName); // and process the stream, will close automatically at exit from scope

如果您尝试返回本地fstream(即从函数内部),编译器将无法(除非您使用C ++ 11),因为fstream是非可复制。在C ++ 11中,编译器将使用移动语义并将本地fstream移动到返回的流中。所以原则上这应该有效:

fstream fileReading(const string& signalFile)
{
    fstream fileName;
    fileName.open(signalFile, ios::in | ios::binary);

    //does more stuff here

    // fileName.close(); // do not close it here
    return fileName;
}

然后用作

fstream f = fileReading("test.txt");

但是,对于可移动流的支持似乎在g ++ 4.9中得到了解决(在g ++ 5和clang ++中工作)。这就是为什么最好只是通过引用传递流并返回引用。