1 // Common/StdInStream.cpp
2 
3 #include "StdAfx.h"
4 
5 #include <tchar.h>
6 
7 #include "StdInStream.h"
8 #include "StringConvert.h"
9 #include "UTFConvert.h"
10 
11 #ifdef _MSC_VER
12 // "was declared deprecated" disabling
13 #pragma warning(disable : 4996 )
14 #endif
15 
16 static const char kIllegalChar = '\0';
17 static const char kNewLineChar = '\n';
18 
19 static const char *kEOFMessage = "Unexpected end of input stream";
20 static const char *kReadErrorMessage  ="Error reading input stream";
21 static const char *kIllegalCharMessage = "Illegal character in input stream";
22 
23 static LPCTSTR kFileOpenMode = TEXT("r");
24 
25 extern int g_CodePage;
26 
27 CStdInStream g_StdIn(stdin);
28 
Open(LPCTSTR fileName)29 bool CStdInStream::Open(LPCTSTR fileName)
30 {
31   Close();
32   _stream = _tfopen(fileName, kFileOpenMode);
33   _streamIsOpen = (_stream != 0);
34   return _streamIsOpen;
35 }
36 
Close()37 bool CStdInStream::Close()
38 {
39   if (!_streamIsOpen)
40     return true;
41   _streamIsOpen = (fclose(_stream) != 0);
42   return !_streamIsOpen;
43 }
44 
~CStdInStream()45 CStdInStream::~CStdInStream()
46 {
47   Close();
48 }
49 
ScanStringUntilNewLine(bool allowEOF)50 AString CStdInStream::ScanStringUntilNewLine(bool allowEOF)
51 {
52   AString s;
53   for (;;)
54   {
55     int intChar = GetChar();
56     if (intChar == EOF)
57     {
58       if (allowEOF)
59         break;
60       throw kEOFMessage;
61     }
62     char c = char(intChar);
63     if (c == kIllegalChar)
64       throw kIllegalCharMessage;
65     if (c == kNewLineChar)
66       break;
67     s += c;
68   }
69   return s;
70 }
71 
ScanUStringUntilNewLine()72 UString CStdInStream::ScanUStringUntilNewLine()
73 {
74   AString s = ScanStringUntilNewLine(true);
75   int codePage = g_CodePage;
76   if (codePage == -1)
77     codePage = CP_OEMCP;
78   UString dest;
79   if (codePage == CP_UTF8)
80     ConvertUTF8ToUnicode(s, dest);
81   else
82     dest = MultiByteToUnicodeString(s, (UINT)codePage);
83   return dest;
84 }
85 
ReadToString(AString & resultString)86 void CStdInStream::ReadToString(AString &resultString)
87 {
88   resultString.Empty();
89   int c;
90   while ((c = GetChar()) != EOF)
91     resultString += char(c);
92 }
93 
Eof()94 bool CStdInStream::Eof()
95 {
96   return (feof(_stream) != 0);
97 }
98 
GetChar()99 int CStdInStream::GetChar()
100 {
101   int c = fgetc(_stream); // getc() doesn't work in BeOS?
102   if (c == EOF && !Eof())
103     throw kReadErrorMessage;
104   return c;
105 }
106 
107 
108