繁体   English   中英

编译C ++代码时出错(无效转换)

[英]Getting error compiling C++ code (Invalid Conversion)

在文件下编译时,我void*无效转换为FILE*错误。 它以文件名作为参数并尝试打开文件,如果文件打开则返回文件指针,否则返回NULL

#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;
}

您的“打开”声称返回“ 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
    }
}

您不能将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
}

myFile是一个ifstream对象。

您不能将其作为FILE指针返回

你也不能返回std::ifstream因为它没有复制构造函数

您可以通过引用传递它

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

在主要

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

}

尝试这个:-

std::ifstream open(const char* filename)

代替

FILE* open(const char filename[])

还要尝试从您的main函数return一些值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM