[英]How to write a properly function in C for file pointer?
我能夠編寫以下主程序:
int main(){
#include <stdio.h>
#include <stdlib.h>
FILE *fpointer = fopen("file.txt", "r+");
if (fpointer == NULL){
printf("file does not exist!\n");
return EXIT_FAILURE;
fclose(fpointer);
return 0;
}
但是,我無法將其拆分為新的 function(打開文件並檢查是否存在)。 我想調用新的 function checkFileExistence()
。 這就是我嘗試編寫它的方式:
#include <stdio.h>
#include <stdlib.h>
int checkFileExistence(char* filepath){
FILE* file=fopen(filepath,"w");
if (file == NULL){
printf("File does not exist!");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int main(){
char* filepath = "test.txt";
FILE* new_file_pointer=checkFileExistence(filepath);
fclose(new_file_pointer);
return 0;
}
但是我現在幾個小時都在出錯。 此時的錯誤是:
file.c:19:8: warning: incompatible integer to pointer conversion initializing 'FILE *'
(aka 'struct __sFILE *') with an expression of type 'int' [-Wint-conversion]
FILE* new_file_pointer=checkFileExistence(filepath);
如何正確編碼? 我只想使用自己的 function 來檢查文件的存在,而不是將所有內容放入主 function 中。 預先感謝您的回答。 我研究了數據類型的理論,但仍然無法正確使用它,因為指針以某種方式讓我感到困惑。 非常感謝。 我喜歡這個平台,並始終感謝所有答案!
checkFileExistence()
的返回類型是int
。 但是在main()
中,您將其分配給數據類型FILE
的變量。
嘗試改變
FILE* new_file_pointer=checkFileExistence(filepath);
至
int existance_status = checkFileExistence(filepath);
但這會導致變量 scope 錯誤,您可能也需要注意這一點!
嗯....如果你在 main 的主體中#include <stdio.h>
你可能會遇到麻煩,因為這將stdio.h
中所有定義的 scope 限制在 main 的主體中。 因此,如果您需要在 main 之后編寫的不同 function 中的stdio.h
定義,則必須再次包含它。 但這不起作用,因為stdio.h
定義了一個標志,以避免將其再次包含在同一編譯單元中,以防止雙重定義錯誤。 因此,切勿在 function 或由{
和}
分隔的塊中使用#include <stdio.h>
。
無論如何,您的第二段代碼中有幾個問題:
#include <stdio.h>
#include <stdlib.h>
int checkFileExistence(char* filepath){
如果您返回int
,則不能將其分配給FILE *
變量,就像您在main
例程中所做的那樣。 最好使用FILE * checkFileExistence(char* filepath)
作為 function 的原型。
FILE* file=fopen(filepath,"w");
if (file == NULL){
printf("File does not exist!");
return EXIT_FAILURE;
EXIT_FAILURE
是 integer,但您想返回一個指針。 最好exit(EXIT_FAILURE);
這樣程序就結束了(如果無法打開文件,還能做什么?)或者return NULL
,表示調用代碼在打開文件時遇到了問題。
}
return EXIT_SUCCESS;
您應該返回從fopen
獲得的FILE *
,否則您將無法在main
中進行任何操作。 更好地寫入return file;
.
}
int main(){
char* filepath = "test.txt";
FILE* new_file_pointer=checkFileExistence(filepath);
fclose(new_file_pointer);
return 0;
}
因此,您的文件在編輯后應類似於:
#include <stdio.h>
#include <stdlib.h>
FILE *checkFileExistence(char* filepath){
FILE* file=fopen(filepath,"w");
if (file == NULL){
printf("File does not exist!");
exit(EXIT_FAILURE);
/* or return NULL; */
}
return file;
}
int main(){
char* filepath = "test.txt";
FILE* new_file_pointer=checkFileExistence(filepath);
/* it should be convenient you say something, as you'll get the file
* opened and closed without you seeing anything at the terminal. */
if (new_file_pointer != NULL) {
printf("File opened successfully\n");
}
fclose(new_file_pointer);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.