1// Common/ListFileUtils.cpp
2
3#include "StdAfx.h"
4
5#include "MyWindows.h"
6#include "../Windows/FileIO.h"
7
8#include "ListFileUtils.h"
9#include "StringConvert.h"
10#include "UTFConvert.h"
11
12static const char kQuoteChar     = '\"';
13static void RemoveQuote(UString &s)
14{
15  if (s.Length() >= 2)
16    if (s[0] == kQuoteChar && s[s.Length() - 1] == kQuoteChar)
17      s = s.Mid(1, s.Length() - 2);
18}
19
20bool ReadNamesFromListFile(LPCWSTR fileName, UStringVector &resultStrings, UINT codePage)
21{
22  NWindows::NFile::NIO::CInFile file;
23  if (!file.Open(fileName))
24    return false;
25  UInt64 length;
26  if (!file.GetLength(length))
27    return false;
28  if (length > ((UInt32)1 << 31))
29    return false;
30  AString s;
31  char *p = s.GetBuffer((int)length + 1);
32  UInt32 processed;
33  if (!file.Read(p, (UInt32)length, processed))
34    return false;
35  p[(UInt32)length] = 0;
36  s.ReleaseBuffer();
37  file.Close();
38
39  UString u;
40  #ifdef CP_UTF8
41  if (codePage == CP_UTF8)
42  {
43    if (!ConvertUTF8ToUnicode(s, u))
44      return false;
45  }
46  else
47  #endif
48    u = MultiByteToUnicodeString(s, codePage);
49  if (!u.IsEmpty())
50  {
51    if (u[0] == 0xFEFF)
52      u.Delete(0);
53  }
54
55  UString t;
56  for (int i = 0; i < u.Length(); i++)
57  {
58    wchar_t c = u[i];
59    if (c == L'\n' || c == 0xD)
60    {
61      t.Trim();
62      RemoveQuote(t);
63      if (!t.IsEmpty())
64        resultStrings.Add(t);
65      t.Empty();
66    }
67    else
68      t += c;
69  }
70  t.Trim();
71  RemoveQuote(t);
72  if (!t.IsEmpty())
73    resultStrings.Add(t);
74  return true;
75}
76