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;
}
fgetcreturns anintnot achar. - Some programmer dudefgetc, I don't even get a warning, and the results are just as expected. What would you suggest to replacefgetc? - J. Bermansizeof(char*)is 4 or 8. It's enough to allocatestrlen(...) + 1bytes. And you should usestrcpyto copy the string, now you change the pointer to point to the local variable (so still return a pointer to a local variable). - Some programmer dude' ' == (bufferString[numCharRead] = fgetc(fPtr)) ? 0 : numCharRead++;... this is a really convoluted way of expressingif ((bufferString[numCharRead] = fgetc(fPtr))) numCharRead++;. - dreamlax