我正在尝试编写一个函数来检查文件是否已打开,如果没有,则打开它。该文件在 main 中定义并作为参数传递给函数。代码有效,但是当我尝试向主函数添加某些内容(如 int i; 一样简单)时,程序崩溃,错误消息为: Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) 行中因此,对于“if (*subor==NULL) {”,我认为文件的存储方式存在问题。
这是我的代码:
int funkcia_v (FILE **subor) {
if (*subor==NULL) {
printf("File has not been opened yet.\n");
*subor = fopen("pathtothefile.txt","r");
if (*subor==NULL) {
printf("File not opened.\n");
}
}
else {
printf("File already opened.\n");
}
printf("\n");
return 0;
}
int main() {
char c;
//if i type int i; here, the program crashes
FILE* subor;
printf("Start the function.\n");
c = getchar();
while (1) {
if (c=='v') {
funkcia_v(subor);
}
else if (c=='k') {
break;
}
else {
printf("Unknown key, try again.");
printf("\n");
}
fflush(stdin);
c = getchar();
}
return 0;
}
对这可能是什么有什么想法吗?
因此,结合上面所有的建设性意见, 我们有这个。
#include <stdio.h>
#include <stdlib.h>
int funkcia_v (FILE **subor) {
if (*subor==NULL) {
printf("File has not been opened yet.\n");
*subor = fopen("pathtothefile.txt","r");
if (*subor==NULL) {
printf("File not opened.\n");
}
else printf("File just opened.\n");
}
else {
printf("File already opened.\n");
}
printf("\n");
return 0;
}
int main() {
char c;
int i; // doesn't crash
FILE* subor = NULL;
printf("Start the function.\n");
c = getchar();
while (1) {
if (c=='v') {
funkcia_v(&subor);
}
else if (c=='k') {
break;
}
else if (c!=10) {
printf("Unknown key %c, try again.",c);
printf("\n");
}
c = getchar();
}
if (subor!=NULL) fclose (subor);
return 0;
}
注意,它将文件指针传递给函数。
你不是 FIITkar 同胞吗? //////