あなたの「open」は「FILE *」を返すと主張していますが、実際にはifstreamを返します。
「open」は標準ライブラリの「open」関数と競合するため、これも関数名の選択として不適切である可能性があることに注意してください。
ifstream を返すか、パラメータとして初期化することができます。
bool openFile(ifstream& file, const char* filename)
{
file.open(filename);
return !file.is_open();
}
int main(int argc, const char* argv[])
{
ifstream file;
if (!openFile(file, "prefixRanges.txt"))
// we have a problem
}
本当に関数からファイルを返したい場合:
ifstream openFile(const char* filename)
{
ifstream myFile;
myFile.open(filename);
return myFile;
}
int main(int argc, const char* argv[])
{
ifstream myFile = openFile("prefixRanges.txt");
if (!myFile.is_open())
// that's no moon.
}
ただし、これが示すように、「openFile」がさらに何かを行う場合を除き、少し冗長です。比較:
int main(int argc, const char* argv[])
{
ifstream file("prefixRanges.txt");
if (!file.is_open()) {
std::cout << "Unable to open file." << std::endl;
return 1;
}
// other stuff
}
ただし、実際に必要なものが FILE* である場合は、次のように C ライクなコードを記述する必要があります。
#include <cstdio>
FILE* openFile(const char* filename)
{
FILE* fp = std::fopen(filename, "r");
return fp;
}
int main(int argc, const char* argv[])
{
FILE* fp = openFile("prefixRanges.txt");
if (!fp) {
// that's no moon, or file
}
}
あるいは単に
#include <cstdio>
int main(int argc, const char* argv[])
{
FILE* fp = std::fopen("prefixRanges.txt", "r");
if (!fp) {
// that's no moon, or file
}
}