這是我正在嘗試使用的基本代碼。
void test(){
FILE *input;
input = fopen("input.txt.", "r");
}
所以我試圖檢查檔案之前是否已經打開,這意味著之前呼叫過一次 void test() 函式。我真的不知道該怎么做,我嘗試了 while 和 if。像這樣。
void test(){
FILE *input;
int open = 0;
while (open == 0){
input = fopen("input.txt", "r");
if (input == NULL){
printf("File wasnt opened.\n");
}
if (input != NULL){
printf("File is opened.\n");
}
open = open 1;
}
if(open!=0){
printf("file is already opened.\n");
}
}
uj5u.com熱心網友回復:
使用區域靜態變數。
void test (void)
{
static bool called_before = false;
if(called_before)
{
do_this();
}
else
{
do_that();
called_before = true;
}
}
uj5u.com熱心網友回復:
假設您的意圖是test打開檔案一次,但每次呼叫時都從檔案中讀取,您可以使input靜態:
void test(void)
{
/* Since input is static, it will be initialized with NULL when the
program starts and we will retain its value between calls to
the function.
*/
static FILE *input = NULL;
// If input has not been set for an open file yet, try to open it.
if (!input)
{
input = fopen("input.txt", "r");
if (!input)
{
fprintf(stderr, "Error, unable to open input.txt.\n");
exit(EXIT_FAILURE);
}
}
for (int c = fgetc(input); c != EOF && c != '\n'; c = fgetc(input))
putchar(c);
putchar('\n');
}
注意通常應該避免使用靜態物件,因為它們會使程式狀態復雜化,因此可能會導致更多錯誤。在學生程式中與它們一起玩以了解它們的作業原理是可以的,但它們在實際應用程式中的使用應該受到限制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348682.html
標籤:C
上一篇:無法弄清楚如何檢查C代碼中的值
