目标: 如何成功实现EOF以阻止无限循环?
调用函数的部分:
do {
pId = readInputField(fptr, DELIMITER_SPACE);
pName = readInputField(fptr, DELIMITER_SEMICOLON);
pDob = readInputField(fptr, DELIMITER_SPACE);
pHobbyList = readInputField(fptr, DELIMITER_NEWLINE);
} while (NULL != pId
&& NULL != pName
&& NULL != pDob
&& NULL != pHobbyList);
功能定义:
char* readInputField(FILE* fPtr, const char delimiter) {
int numCharRead;
char bufferString[MAX_LENGTH_INPUT];
char *pBufferString;
numCharRead = 0;
// flush: if spaces are found
' ' == (bufferString[numCharRead] = fgetc(fPtr)) ? 0 : numCharRead++;
// get chracter array before delimiter
while (delimiter != bufferString[numCharRead - 1]
&& numCharRead < MAX_LENGTH_INPUT) {
bufferString[numCharRead++] = fgetc(fPtr);
}
// exclude delimiter from the string
bufferString[numCharRead - 1] = '\0';
printf("numCharRead= \"%d\"\n", numCharRead);
printf("delimiter: \"%c\"\n", delimiter);
printf("bufferString: \"%s\"\n", bufferString);
pBufferString = malloc(sizeof(char*) * strlen(bufferString));
/* deleted:
pBufferString = bufferString;
return EOF == bufferString[numCharRead - 1] ? NULL : pBufferString;
*/
}
示例输入:
VIC Lee, Victoria; 02/25/90 Knitting;Photography;Dance;
示例输出:
numCharRead= "4"
delimiter: " "
bufferString: "VIC"
numCharRead= "14"
delimiter: ";"
bufferString: "Lee, Victoria"
numCharRead= "9"
delimiter: " "
bufferString: "02/25/90"
numCharRead= "28"
delimiter: "
"
bufferString: "Knitting;Photography;Dance;"
// after this, infinite loop begins with garbage data
我的电话是查看上面的return语句。由于某种原因,它不会检测它是否是EOF。
任何帮助表示赞赏!谢谢!
更新 谢谢@JoachimPileborg!我已在下面更新了我的代码:
// check for EOF
if(bufferString[numCharRead-1] == EOF) {
return NULL;
} else {
pBufferString = malloc(sizeof(char*));
strcpy(pBufferString, bufferString);
return pBufferString;
}
答案 0 :(得分:2)
检查您从文件中读取的EOF
// flush: if spaces are found
' ' == (bufferString[numCharRead] = fgetc(fPtr)) ? 0 : numCharRead++;
if(bufferString[numCharRead-1] == EOF)
return NULL;
while (delimiter != bufferString[numCharRead - 1]
&& numCharRead < MAX_LENGTH_INPUT) {
bufferString[numCharRead++] = fgetc(fPtr);
/* check for EOF */
if(bufferString[numCharRead-1] == EOF)
return NULL;
}
你也有@Joachim Pileborg评论中提到的问题
fgetc
返回int
而不是char
bufferString
。答案 1 :(得分:1)
无法在评论中编写代码,因此我将其作为答案发布。
您在问题中拥有(或至少拥有)此代码:
pBufferString = malloc(sizeof(char*) * strlen(bufferString));
pBufferString = bufferString;
return EOF == bufferString[numCharRead - 1] ? NULL : pBufferString;
在上面的第一行中,您分配内存并使pBufferString
指向该内存。
在第二行中,然后使pBufferString
指向本地数组bufferString
,因此您不再有指向使用malloc
分配的内存的指针,从而导致内存泄漏(当你稍后尝试free
那个指针时,可能会崩溃。
然后返回pBufferString
,它现在指向本地数组,导致未定义的行为,因为本地数组占用的堆栈内存在函数返回后不再有效。
除了上述问题,您可以根据需要分配几乎四到八倍的内存。指针的大小是四个或八个字节(取决于您是在32位还是64位平台上),但char
只有一个字节。使用strlen(bufferString) + 1
作为分配大小就足够了:
pBufferString = malloc(strlen(bufferString) + 1);
您需要+ 1
,因为字符串终止符不包含在字符串长度中。