fgets()不会将文件中的内容读取到2d数组

时间:2014-07-24 01:41:55

标签: c arrays string fgets

fgets语句未收集calendarLog文件流到events[][]数组中的任何内容。我的calendarLog.txt有五行:

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]);
        }

1 个答案:

答案 0 :(得分: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]);
     }
 }