2014-09-25 152 views
0

我創建了一個c程序,以便在調用某個特定函數時,它應該創建文本文件,這是c /某些文件夾名/日誌文件中的路徑。函數被調用和終止的時間,日期將被存儲到文本文件中。我已經嘗試了下面的代碼。如何用c語言調用函數時重複寫入文本文件

function() { 
    FILE *fp; 
    char ch; 
    time_t current_time; 
    char* c_time_string; 

    /* Obtain current time as seconds elapsed since the Epoch. */ 
    current_time = time(NULL); 

    if (current_time == ((time_t)-1)) 
    { 
     (void) fprintf(stderr, "Failure to compute the current time."); 
     return EXIT_FAILURE; 
    } 

    /* Convert to local time format. */ 
    c_time_string = ctime(&current_time); 

    if (c_time_string == NULL) 
    { 
     (void) fprintf(stderr, "Failure to convert the current time."); 
     return EXIT_FAILURE; 
    } 


    fp=fopen("C:\\X2.6\\X_LogFiles\\file.txt","w");); 

    /* Print to stdout. */ 

    while((ch=getchar())!=EOF) 
    putc(c_time_string,fp); 
    fclose(fp); 

    return 0; 
} 

我是一個新的初學者在c。我探討,但我能不能找到函數寫時間和數據的文本文件,當我再次調用該函數

感謝您的答覆提前

回答

0

在文件中的數據被刪除,因爲你得到了清除以寫模式打開文件(fopen()命令中的「w」)

fp=fopen("C:\\X2.6\\X_LogFiles\\file.txt","w"); 

無論何時以「w」模式打開文件。如果文件不存在,它將被創建。但如果文件存在該文件將被清空,其所有數據被刪除,然後打開

如果你想追加(添加到已存在的文件)到文件,你應該使用「a」inplace的「w」。如果文件不存在,附加模式將創建該文件。但是,如果文件在那裏,那麼它只是打開添加(追加)數據到它

0

使用printf寫入文件的時間。

printf(file_descriptor, "control_String");

這將是

printf(fp," %s\n", asctime (current_time));

以附加模式也打開文件a

fFILE *fp; 
char ch; 
time_t current_time; 
char* c_time_string; 

/* Obtain current time as seconds elapsed since the Epoch. */ 
time(&current_time); 

if (current_time == ((time_t)-1)) 
{ 
    (void) fprintf(stderr, "Failure to compute the current time."); 
    return EXIT_FAILURE; 
} 

/* Convert to local time format. */ 
c_time_string = ctime(&current_time); 

if (c_time_string == NULL) 
{ 
    (void) fprintf(stderr, "Failure to convert the current time."); 
    return EXIT_FAILURE; 
} 


fp=fopen("C:\\X2.6\\X_LogFiles\\file.txt","a");); 

/*changed here*/ 

fprintf(fp,"%s",c_time_string); 


fclose(fp); 

返回0; }

+0

我在printf語句中遇到下面的錯誤在參數1中輸入錯誤到'printf';找到'指向FILE'指向'const char'的指針。 將參數1中的錯誤輸入爲'asctime';發現'time_t'期望'指向const struct tm'的指針。 – user2968080 2014-09-26 16:33:54

+0

對不起......這是'fprintf'不是'printf'編輯原文 – nu11p01n73R 2014-09-26 16:35:39

+0

在參數1中輸入錯誤爲'asctime';發現'time_t'期望'指向const struct tm'的指針。 我仍然面臨fprinf語句 – user2968080 2014-09-27 02:22:16