C语言 将 FILE 指针传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33378000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:11:17  来源:igfitidea点击:

Passing FILE pointer to a function

cpointers

提问by Sir DrinksCoffeeALot

I'm little bit confused over here, not quite sure about this. What I'm trying to do is to pass the name of a file through terminal/cmdthat will be opened and read from.

我在这里有点困惑,不太确定这一点。我想要做的是通过terminal/传递文件的名称,该文件cmd将被打开和读取。

myfunction(char* fileName, FILE* readFile)
{
    if((readFile = fopen(fileName,"r")) == NULL)
    {
        return FILE_ERROR;
    }
    return FILE_NO_ERROR;
}

int main(int argc, char **argv)
{
FILE* openReadFile;
    if(myfunction(argv[1], openReadFile) != FILE_NO_ERROR)
    {
        printf("\n %s : ERROR opening file. \n", __FUNCTION__);
    }
}

My question is if i pass a pointer openReadFileto myfunction()will a readFilepointer to opened file be saved into openReadFilepointer or do i need to put *readFilewhen opening.

我的问题是,如果我传递一个指针openReadFilemyfunction()readFile指向打开文件的指针保存到openReadFile指针中,还是*readFile在打开时需要放置。

回答by mksteve

FILE * needs to be a pointer, so in main openReadFile stays as a pointer. myfunction takes **, so we can update the FILE * with the result from fopen *readFile = fopen...updates the pointer.

FILE * 需要是一个指针,所以在主 openReadFile 中仍然是一个指针。myfunction 需要 **,因此我们可以使用 fopen 的结果更新 FILE * *readFile = fopen...更新指针。

int myfunction(char* fileName, FILE** readFile) /* pointer pointer to allow pointer to be changed */
{
    if(( *readFile = fopen(fileName,"r")) == NULL)
    {
        return FILE_ERROR;
    }
    return FILE_NO_ERROR;
}

int main(int argc, char **argv)
{
    FILE* openReadFile; /* This needs to be a pointer. */
    if(myfunction(argv[1], &openReadFile) != FILE_NO_ERROR) /* allow address to be updated */
    {
        printf("\n %s : ERROR opening file. \n", __FUNCTION__);
    }
}