如何打开文件以在单独的函数中读取而不会出现分段错误?

问题描述 投票:0回答:1

当我在单个函数中打开文件时,它打开时没有错误。

void fileOpen(char fileName[]){
    FILE *file;
    file = fopen(fileName, "r");
    if(file != NULL) {
        printf("Successfully opened.");
    }
}

输出:

Successfully opened.

但是,当我尝试将进程移至单独的函数时,文件会打开,但出现分段错误。

void fileOpen(FILE file, char fileName[]){
    file = fopen(fileName, "r");
    if(file != NULL) {
        printf("Successfully opened.");
    }
}

void fileStart(){
    FILE *mainFile;
    char name[] = "file.txt";
    fileOpen(mainFile, name);
}

输出:

Successfully opened.
segmentation fault (core dumped) ./executable

如果这是我传递变量的方式的错误,请解释。指针对我来说是一个弱点。

c segmentation-fault
1个回答
3
投票

1) 您希望函数

void fileOpen
修改其第一个参数,您希望其类型为 FILE*。因此,第一个参数应该是指向此类指针的指针:

void fileOpen(FILE** file, char fileName[]){
    *file = fopen(fileName, "r");
    if(*file != NULL) {
        printf("Successfully opened.");
    }
}

2) 在

fileStart
中,通过提供所需的所有参数和正确的类型来正确调用函数:

void fileStart(){
    FILE *mainFile;
    fileOpen(&mainFile, "someFileName");
}

p.s:你最好让函数

fileOpen
返回指针而不是修改参数。实际上,做这件事的“好”方法是:

   FILE* fileOpen(char fileName[]){
        FILE* file = fopen(fileName, "r");
        if(file != NULL) {
            printf("Successfully opened.");
        }
        return file;
    }
    void fileStart(){
        FILE* mainFile = fileOpen("someFileName");
        if(mainFile == NULL){
         ... error, do something
        }

    }
© www.soinside.com 2019 - 2024. All rights reserved.