OBJECTIVE:
How to implement EOF successfully to stop the infinite loop?
part where the function is called:
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);
function definition:
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;
*/
}
sample input:
VIC Lee, Victoria; 02/25/90 Knitting;Photography;Dance;
sample output:
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
My call is to look at return statement above. For some reason, it does not detect if it is EOF.
Any help is appreciated! Thanks!
updated:
Thanks @JoachimPileborg! I have updated my code below:
// check for EOF
if(bufferString[numCharRead-1] == EOF) {
return NULL;
} else {
pBufferString = malloc(sizeof(char*));
strcpy(pBufferString, bufferString);
return pBufferString;
}
Check for
EOFwhere you read from file, asYou also have problems that mentioned in comments by @Joachim Pileborg
fgetcreturnsintnotcharbufferStringwhich is local to function.