如何在不出现分段错误的情况下打开文件以在单独的函数中读取?
How do I open a file for reading in a separate function without getting a segmentation fault?
当我在单个函数中打开文件时,它打开时没有错误。
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
如果我传递变量的方式有误,请解释。指针对我来说是一个弱点。
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
return 指针而不是修改一个参数。实际上,"good" 做这件事的方法是:
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
}
}
当我在单个函数中打开文件时,它打开时没有错误。
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
如果我传递变量的方式有误,请解释。指针对我来说是一个弱点。
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
return 指针而不是修改一个参数。实际上,"good" 做这件事的方法是:
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
}
}