[4/4] cmd: Simplify WCMD_fgets

Frédéric Delanoy frederic.delanoy at gmail.com
Tue Oct 4 04:06:19 CDT 2011


Factorize handling of console/file reads where possible
---
 programs/cmd/batch.c |   50 ++++++++++++++++++++++----------------------------
 1 files changed, 22 insertions(+), 28 deletions(-)

diff --git a/programs/cmd/batch.c b/programs/cmd/batch.c
index 07851a5..0aff18b 100644
--- a/programs/cmd/batch.c
+++ b/programs/cmd/batch.c
@@ -190,45 +190,39 @@ WCHAR *WCMD_fgets(WCHAR *buf, int noChars, HANDLE h, const BOOL is_console_handl
 {
   DWORD charsRead;
   BOOL status;
+  LARGE_INTEGER filepos;
+  int i;
 
   /* We can't use the native f* functions because of the filename syntax differences
      between DOS and Unix. Also need to lose the LF (or CRLF) from the line. */
 
-  if (is_console_handle) {
-    status = ReadConsoleW(h, buf, noChars, &charsRead, NULL);
-    if (!status) return NULL;
-    if (buf[charsRead-2] == '\r')
-      buf[charsRead-2] = '\0'; /* Strip \r\n */
-    else {
-      /* Truncate */
-      buf[noChars-1] = '\0';
-    }
-  } else {
-    LARGE_INTEGER filepos;
-    int i;
-
+  if (!is_console_handle) {
     /* Save current file position */
     filepos.QuadPart = 0;
     SetFilePointerEx(h, filepos, &filepos, FILE_CURRENT);
+  }
 
-    status = WCMD_ReadFile(h, buf, noChars, &charsRead, 0);
-    if (!status || charsRead == 0) return NULL;
-    for (i = 0; i < charsRead; i++) {
-        if (buf[i] == '\n' || buf[i] == '\r')
-            break;
-    }
+  status = WCMD_ReadFile(h, buf, noChars, &charsRead, is_console_handle);
+  if (!status || charsRead == 0) return NULL;
 
-    if (i != charsRead) {
-      /* Sets file pointer to the start of the next line, if any */
-      filepos.QuadPart += i + 1 + (buf[i] == '\r' ? 1 : 0);
-      SetFilePointerEx(h, filepos, NULL, FILE_BEGIN);
-    } else {
-      /* File pointer positioned correctly already; truncate at the correct place */
-      i--;
-    }
-    buf[i] = '\0';
+  /* Find first EOL */
+  for (i = 0; i < charsRead; i++) {
+    if (buf[i] == '\n' || buf[i] == '\r')
+      break;
+  }
+
+  if (!is_console_handle) {
+    /* Sets file pointer to the start of the next line, if any */
+    filepos.QuadPart += i + 1 + (buf[i] == '\r' ? 1 : 0);
+    SetFilePointerEx(h, filepos, NULL, FILE_BEGIN);
   }
 
+  /* Truncate at EOL (or end of buffer) */
+  if (i == noChars)
+    i--;
+
+  buf[i] = '\0';
+
   return buf;
 }
 
-- 
1.7.6.3




More information about the wine-patches mailing list