你的「open」聲明返回「FILE *」,但實際返回一個ifstream。
請注意,「打開」與標準庫的「打開」功能衝突,所以這也可能是功能名稱的一個糟糕的選擇。
您可以返回一個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
}
如果你真正需要的,不過,是一個文件*,你必須寫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
}
}
轉換從NULL到FILE *是最少的問題。你也從std :: ifstream轉換爲FILE *,這是完全不同的結構,更不用說一個是局部變量而另一個是指針。另外,你沒有從main返回一個值。 –