我正在嘗試撰寫一個函式來檢查檔案是否已打開,如果沒有,請打開它。該檔案在 main 中定義,并作為引數傳遞給函式。該代碼有效,但是當我嘗試向主函式添加一些內容時(就像 int i; 一樣簡單),程式崩潰并且錯誤訊息是:執行緒 1:EXC_BAD_ACCESS(代碼=1,地址=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;
}
關于這可能是什么的任何想法?
uj5u.com熱心網友回復:
所以,結合上面所有的建設性意見,我們有這個。
#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;
}
請注意,它將檔案指標的指標傳遞給函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441817.html
上一篇:檢查串列中是否沒有要洗掉的內容
