CSV to HTML translation: Difference between revisions

C
(Added Perl 5.)
(C)
Line 18:
For extra credit, ''optionally'' allow special formatting for the
first row of the table as if it is the tables header row.
 
=={{header|C}}==
This produces a full bare html (tidy gives two warnings) with styles embedded but not
"inlined"; it does not escape characters that does not need to be escaped (provided
that the correct encoding matching the encoding of the input is given; currently
hard-endoded UTF-8).
<lang c>#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
 
#define BUF_LEN 12
 
void html_min_header(const char *enc, const char *title)
{
printf("<html><head><title>%s</title>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\">"
"<style type=\"text/css\"><!--"
"th {font-weight:bold;text-align:left;background-color:yellow}"
"table,td,th {border:1px solid #000;border-collapse:collapse}"
"td {background-color:cyan}"
"td,th {padding:5px}//-->"
"</style></head><body>", title, enc);
}
 
void html_min_footer(void)
{
printf("</body></html>");
}
 
void escape_html(char *o, int c)
{
static const char *specials = "<>&";
static const char *map[] = { "&lt;", "&gt;", "&amp;"};
ptrdiff_t pos;
char *p;
if ( (p = strchr(specials, c)) != NULL ) {
pos = p - specials;
if (o != NULL) strcpy(o, map[pos]);
} else {
o[0] = c;
o[1] = '\0';
}
}
 
void add_column(const char *type, int c)
{
char buf[BUF_LEN];
 
if ( c == '\n' ) return;
 
printf("<%s>", type);
for(; c != EOF && c != '\n'; c = getchar()) {
if (c == ',') {
printf("</%s><%s>", type, type);
continue;
}
escape_html(buf, c);
printf("%s", buf);
}
printf("</%s>", type);
}
 
enum mode {
FIRST = 1, NEXT
};
int main(int argc, char **argv)
{
int c;
enum mode status = FIRST;
 
html_min_header("utf-8", "CSV converted into HTML");
 
printf("<table>");
while( (c = getchar()) != EOF ) {
printf("<tr>");
switch(status) {
case FIRST:
add_column("th", c);
status = NEXT;
break;
case NEXT:
default:
add_column("td", c);
break;
}
printf("</tr>");
}
printf("</table>");
 
html_min_footer();
 
return EXIT_SUCCESS;
}</lang>
 
=={{header|OCaml}}==