从CGI输出中删除不需要的字符

时间:2011-06-16 02:03:45

标签: html c backend

我有一个用C语言编写的网站后端,它将HTML页眉和页脚模板与动态生成的内容粘贴在一起。出于某种原因,在每次调用displayTemplate()之后都会附加一个不需要的'ÿ'(变音符号y)字符(ASCII 152)。此字符是不需要的,不是文件的一部分。如何防止输出?感谢。

执行此功能的代码如下所示:

#include <stdio.h>
#include <stdlib.h>

void displayTemplate(char *);

int main(void) {
    printf("%s%c%c\n", "Content-Type:text/html;charset=iso-8859-1", 13, 10);
    displayTemplate("templates/mainheader.html");
    /* begin */ 
        printf("<p>Generated site content goes here.</p>"); 
    /* end */
    displayTemplate("templates/mainfooter.html");
    return 0;
}
void displayTemplate(char *path) {  
    char currentChar;
    FILE *headerFile = fopen(path, "r");
    do {
        currentChar = fgetc(headerFile);
        putchar(currentChar);
    } while(currentChar != EOF);
    fclose(headerFile);
}

2 个答案:

答案 0 :(得分:2)

更改循环:

while (true)
{
  currentChar = fgetc(headerFile);
  if (currentChar == EOF) break;
  putchar(currentChar);
}

有可能比逐字节读取更好的方法(例如,读取整个文件,或以64kB的块读取)。

答案 1 :(得分:0)

ISO 8859-1中的

'ÿ'为255。停止尝试打印EOF。 EOF是二进制表示的全部,当减少到8位时,它是255。

相关问题