1 /* fileio.c -- does standard I/O
2
3 (c) 1998-2007 (W3C) MIT, ERCIM, Keio University
4 See tidy.h for the copyright notice.
5
6 CVS Info :
7
8 $Author: arnaud02 $
9 $Date: 2007/05/30 16:47:31 $
10 $Revision: 1.17 $
11
12 Default implementations of Tidy input sources
13 and output sinks based on standard C FILE*.
14
15 */
16
17 #include <stdio.h>
18
19 #include "forward.h"
20 #include "fileio.h"
21 #include "tidy.h"
22
23 typedef struct _fp_input_source
24 {
25 FILE* fp;
26 TidyBuffer unget;
27 } FileSource;
28
filesrc_getByte(void * sourceData)29 static int TIDY_CALL filesrc_getByte( void* sourceData )
30 {
31 FileSource* fin = (FileSource*) sourceData;
32 int bv;
33 if ( fin->unget.size > 0 )
34 bv = tidyBufPopByte( &fin->unget );
35 else
36 bv = fgetc( fin->fp );
37 return bv;
38 }
39
filesrc_eof(void * sourceData)40 static Bool TIDY_CALL filesrc_eof( void* sourceData )
41 {
42 FileSource* fin = (FileSource*) sourceData;
43 Bool isEOF = ( fin->unget.size == 0 );
44 if ( isEOF )
45 isEOF = feof( fin->fp ) != 0;
46 return isEOF;
47 }
48
filesrc_ungetByte(void * sourceData,byte bv)49 static void TIDY_CALL filesrc_ungetByte( void* sourceData, byte bv )
50 {
51 FileSource* fin = (FileSource*) sourceData;
52 tidyBufPutByte( &fin->unget, bv );
53 }
54
55 #if SUPPORT_POSIX_MAPPED_FILES
56 #define initFileSource initStdIOFileSource
57 #define freeFileSource freeStdIOFileSource
58 #endif
TY_(initFileSource)59 int TY_(initFileSource)( TidyAllocator *allocator, TidyInputSource* inp, FILE* fp )
60 {
61 FileSource* fin = NULL;
62
63 fin = (FileSource*) TidyAlloc( allocator, sizeof(FileSource) );
64 if ( !fin )
65 return -1;
66 TidyClearMemory( fin, sizeof(FileSource) );
67 fin->unget.allocator = allocator;
68 fin->fp = fp;
69
70 inp->getByte = filesrc_getByte;
71 inp->eof = filesrc_eof;
72 inp->ungetByte = filesrc_ungetByte;
73 inp->sourceData = fin;
74
75 return 0;
76 }
77
TY_(freeFileSource)78 void TY_(freeFileSource)( TidyInputSource* inp, Bool closeIt )
79 {
80 FileSource* fin = (FileSource*) inp->sourceData;
81 if ( closeIt && fin && fin->fp )
82 fclose( fin->fp );
83 tidyBufFree( &fin->unget );
84 TidyFree( fin->unget.allocator, fin );
85 }
86
TY_(filesink_putByte)87 void TIDY_CALL TY_(filesink_putByte)( void* sinkData, byte bv )
88 {
89 FILE* fout = (FILE*) sinkData;
90 fputc( bv, fout );
91 }
92
TY_(initFileSink)93 void TY_(initFileSink)( TidyOutputSink* outp, FILE* fp )
94 {
95 outp->putByte = TY_(filesink_putByte);
96 outp->sinkData = fp;
97 }
98
99 /*
100 * local variables:
101 * mode: c
102 * indent-tabs-mode: nil
103 * c-basic-offset: 4
104 * eval: (c-set-offset 'substatement-open 0)
105 * end:
106 */
107