【发布时间】:2011-04-10 14:37:32
【问题描述】:
编辑将建议纳入编码和更新问题
我必须在程序中实现一个自动换行功能,并且选择了一个贪心算法
//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(temp, " ");
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
}
}
通过这段代码,我验证了文件被正确读入到 readBuffer 中
fputs(readBuffer, stdout) 命令。但是,第一个 fputs 将 11 写入屏幕,而它应该是 1。然后它会跳过 while 循环并退出。
OutputLines 设置为 0,termHeight 是 termHeight=termios.ws_row-1 调用的结果。
如果 temp 正在将值打印到屏幕上,并且 (outputLines= 0) > termHeight,那么在这种情况下 temp 怎么可能为 null?
【问题讨论】:
-
如果字符串中没有更多标记,
strtok将返回null,也许这就是发生了什么? -
我是这么想的,但文件大小是 1.6KB,里面大约有 90 行文本。为什么会返回null?如果我通过
fputs输出文本而没有strtok,则会显示所有文本。 -
文件中是否有任何 NUL 字符('\0')?这会干扰
strtok()。
标签: c unix malloc segmentation-fault text-processing