2013-09-25 77 views
1

我得到無效轉換從void*FILE*編譯下面的文件時出現錯誤。它需要的文件名作爲參數,並試圖打開該文件,如果文件打開它,否則返回NULL獲取錯誤編譯C++代碼(無效轉換)

#include <iostream> 
#include <fstream> 
using namespace std; 

FILE* open(const char filename[]); 

int main(int argc, char *argv[]) 
{ 
    FILE* fp = open("test.txt"); 
} 

FILE* open(const char filename[]) 
{ 
    ifstream myFile; 
    myFile.open(filename); 
    if(myFile.is_open()) 
     return myFile; 
    else 
     return NULL; 
} 
+3

轉換從NULL到FILE *是最少的問題。你也從std :: ifstream轉換爲FILE *,這是完全不同的結構,更不用說一個是局部變量而另一個是指針。另外,你沒有從main返回一個值。 –

回答

3

你的「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 
    } 
} 
+0

我可能會這樣做,但自從我的學校作業以來,我需要返回一個FILE指針,否則它不會通過測試儀。 – Nakib

+0

@Nakib然後你可能想使用從cstdio fopen(見最後一個例子) – kfsone

+0

@kfsone好吧謝謝,並不是只在C ..打開? – Nakib

1

您不能返回std::ifstream對象FILE*返回 文件指針。嘗試改變:

FILE* open(const char filename[]) 

std::ifstream open(const char* filename) 

和而不是檢查NULL是否已返回,使用std::ifstream::is_open()

std::ifstream is = open("myfile.txt"); 
if (!is.is_open()) { 
    // file hasn't been opened properly 
} 
1

myFileifstream對象。

你不能回擊一個FILE指針

你也不能返回std::ifstream,因爲它沒有一個拷貝構造函數

您可以通過引用傳遞它

bool openFile(ifstream& fin, const char *filename) { 
    fin.open(filename); 
    return fin.is_open(); 
} 

In main

ifstream fin; 
if(!openFile(fin, "input.txt")){ 

} 
+0

我需要做什麼更改才能將其作爲FILE指針 – Nakib

+0

@Nakib使用標準C庫而不是STL來返回它。 –

0

試試這個: -

std::ifstream open(const char* filename) 

代替

FILE* open(const char filename[]) 

也儘量returnmain功能有一定的價值。