2014-07-24 57 views
0

fgets聲明沒有收集從calendarLog文件流的任何物體插入events[][]陣列。我calendarLog.txt中有五條線:與fgets()將不會從文件中讀取內容到二維數組

1/1/1 fds 
2/2/2 dsa 
3/3/3 sal 
4/4/4 444 
5/5/5 555 

printf語句指示輸出一個!還有events[counter],但是,我的輸出語句只是問號,!!!!!,其中五(如果我添加更多行到calendarLog,它會打印更多感嘆號)。爲什麼

while(fgets(events[counter++], EVENT_DESCR_SIZE, calendarLog) != NULL) 

保持真實,但printf("!%s", events[counter])無法打印events[counter]? 所有幫助表示感謝!

FILE *calendarLog; 
char events[MAX_EVENTS][EVENT_DESCR_SIZE], 
     *newLinePos; 
int counter = 0, 
    index1, 
    index2;  

for (index1 = 0; index1 < MAX_EVENTS; index1++) 
    for (index2 = 0; index2 < EVENT_DESCR_SIZE; index2++) 
     events[index1][index2] = 0; 
    if ((calendarLog = fopen("calendarLog.txt", "r")) == NULL) 
    { 
     calendarLog = (fopen("calendarLog.txt", "w")); 
     fprintf(calendarLog, "s\n", eventObject); 
    } 
    else  
    { 
     while (fgets(events[counter++], EVENT_DESCR_SIZE, calendarLog) != NULL) 
     { 
      if ((newLinePos = strchr(events[counter], '\n')) != NULL) //takes the '\n' out 
       *newLinePos = '\0'; //of the events[counter] 
      printf("!%s", events[counter]); 
     } 
+2

'counter'是繼去年的指標。 – BLUEPIXY

+0

喔,我需要重新定位 '++' 感謝 – user134723

+0

'fprintf中(calendarLog, 「S \ n」,eventObject)傳遞;'看起來像它應該有「 」%s的\ n「'作爲格式字符串... – mafso

回答

0

這應該告訴你,你需要知道如何解決這個問題的一切:

FILE *calendarLog; 
char events[MAX_EVENTS][EVENT_DESCR_SIZE]; 
char *newLinePos; 
int counter = 0; 
int index1; 
int index2;  

// initialize the array: events[][] 
for (index1 = 0; index1 < MAX_EVENTS; index1++) 
    for (index2 = 0; index2 < EVENT_DESCR_SIZE; index2++) 
     events[index1][index2] = 0; 




if ((calendarLog = fopen("calendarLog.txt", "r")) == NULL) 
{ // fopen failed 
    calendarLog = (fopen("calendarLog.txt", "w")); 
    fprintf(calendarLog, "%s\n", eventObject); // 's' should be '%s 
} 

else  
{ // fopen successful 

    while (fgets(events[counter++], EVENT_DESCR_SIZE, calendarLog) != NULL) 
    { 
     // following 'if' is looking at 'next' events because counter is already updated 
     // replace '\n' with null to terminate string for following printf 
     if ((newLinePos = strchr(events[counter], '\n')) != NULL) 
      *newLinePos = '\0'; 

     // print the value 
     printf("!%s", events[counter]); 
    } 
} 
相關問題