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 static const char kNewLineChar = '\n';
12 
13 static const char *kEOFMessage = "Unexpected end of input stream";
14 static const char *kReadErrorMessage  ="Error reading input stream";
15 static const char *kIllegalCharMessage = "Illegal character in input stream";
16 
17 static LPCTSTR kFileOpenMode = TEXT("r");
18 
19 extern int g_CodePage;
20 
21 CStdInStream g_StdIn(stdin);
22 
Open(LPCTSTR fileName)23 bool CStdInStream::Open(LPCTSTR fileName) throw()
24 {
25   Close();
26   _stream = _tfopen(fileName, kFileOpenMode);
27   _streamIsOpen = (_stream != 0);
28   return _streamIsOpen;
29 }
30 
Close()31 bool CStdInStream::Close() throw()
32 {
33   if (!_streamIsOpen)
34     return true;
35   _streamIsOpen = (fclose(_stream) != 0);
36   return !_streamIsOpen;
37 }
38 
ScanStringUntilNewLine(bool allowEOF)39 AString CStdInStream::ScanStringUntilNewLine(bool allowEOF)
40 {
41   AString s;
42   for (;;)
43   {
44     int intChar = GetChar();
45     if (intChar == EOF)
46     {
47       if (allowEOF)
48         break;
49       throw kEOFMessage;
50     }
51     char c = (char)intChar;
52     if (c == 0)
53       throw kIllegalCharMessage;
54     if (c == kNewLineChar)
55       break;
56     s += c;
57   }
58   return s;
59 }
60 
ScanUStringUntilNewLine()61 UString CStdInStream::ScanUStringUntilNewLine()
62 {
63   AString s = ScanStringUntilNewLine(true);
64   int codePage = g_CodePage;
65   if (codePage == -1)
66     codePage = CP_OEMCP;
67   UString dest;
68   if (codePage == CP_UTF8)
69     ConvertUTF8ToUnicode(s, dest);
70   else
71     dest = MultiByteToUnicodeString(s, (UINT)codePage);
72   return dest;
73 }
74 
ReadToString(AString & resultString)75 void CStdInStream::ReadToString(AString &resultString)
76 {
77   resultString.Empty();
78   int c;
79   while ((c = GetChar()) != EOF)
80     resultString += (char)c;
81 }
82 
Eof()83 bool CStdInStream::Eof() throw()
84 {
85   return (feof(_stream) != 0);
86 }
87 
GetChar()88 int CStdInStream::GetChar()
89 {
90   int c = fgetc(_stream); // getc() doesn't work in BeOS?
91   if (c == EOF && !Eof())
92     throw kReadErrorMessage;
93   return c;
94 }
95