gpt4 book ai didi

c - fgets() 不会将文件内容读取到二维数组

转载 作者:行者123 更新时间:2023-11-30 17:30:49 24 4
gpt4 key购买 nike

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)

保持 true,但 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]);
}

最佳答案

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

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

关于c - fgets() 不会将文件内容读取到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24923796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com