【问题标题】:fgets() won't read content from file to 2d arrayfgets() 不会将文件中的内容读取到二维数组
【发布时间】:2014-07-24 01:41:54
【问题描述】:

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

【问题讨论】:

  • counter 是最后一个的索引。
  • 哦,我需要重新定位'++'谢谢
  • fprintf(calendarLog, "s\n", eventObject); 看起来应该有 "%s\n" 作为格式字符串...

标签: c arrays string fgets


【解决方案1】:

这应该会告诉您有关如何解决问题的所有信息:

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

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多