String tokenizer- strange behavior with verified array
EDIT to incorporate suggestions to code and update question
I have to implement a word wrap feature in the program, and have chosen a greedy algorithm of
//I use fread to take in the file in one bite, the parse the resulting array. The
//four lines below are from another function.
char *readBuffer= (char *) malloc(sizeof(char) * fileSize);
int size= ftell(fp);
rewind(fp);
size_t result= fread(readBuffer, 1, size, fp);
int spaceLeft= termWidth;
int outputLines=0, tempLength, printCount-0;
char *temp, *newLine="\n";
temp= strtok(readBuffer, " "),
fputs(temp, stdout); //prints out a 11, when should be a 1, then exits
while ((outputLines < termHeight) && (temp != NULL)){
strcat(te开发者_C百科mp, " ");
tempLength= strlen(temp);
if (spaceLeft > tempLength){
fputs(temp, stdout);
spaceLeft -= tempLength+1;
} else {
strcat(newLine, temp);
spaceLeft= termWidth-(tempLength);
outputLines++;
newLines="\n";
}
temp= strtok(NULL, " ");
printCount+= tempLength //debugger display
}
}
With this code, I verified that the file was read in correctly to readBuffer by a
fputs(readBuffer, stdout)
command. However, the first fputs writes a 11 to the screen, when it should be a 1. Then it skips the while loop and exits.
OutputLines is set to 0, and termHeight is the result of a termHeight=termios.ws_row-1
call.
If temp is printing a value to the screen, and (outputLines= 0) > termHeight, how can temp be null in this instance?
Part of the problem may be that fgets
retrieves only a single line from the file. The man page describes this. The code appears to expect that it reads the entire file. Thus, temp would be NULL after that first line is processed (single token if no spaces in it).
Not knowing the length of the text you are reading nor the values of termHeight
or termWidth
, it's not possible to know the execution path. But the segfault is probably occurring on the strlen()
call on the NULL temp
value after that line is processed. While this is not a complete fix, the while
statement should probably use &&
instead of ||
:
while ((outputLines > termHeight) && (temp != NULL){
And depending on how you want to process it, you may need another fgets
call to read the next line after strtok
returns NULL. Or, alternatively, use fread
to retrieve the entire file in one call.
精彩评论