diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index b53d6eb9cc..cb8c7450d9 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -491,15 +491,7 @@ readfile(const char *path)
 	char	   *buffer;
 	int			c;
 
-#ifdef WIN32
-	/*
-	 * On Windows, we have to open the file in text mode so that carriage
-	 * returns are stripped.
-	 */
-	if ((infile = fopen(path, "rt")) == NULL)
-#else
 	if ((infile = fopen(path, "r")) == NULL)
-#endif
 	{
 		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
 				progname, path, strerror(errno));
diff --git a/src/port/open.c b/src/port/open.c
index a3ad946a60..9174cdce66 100644
--- a/src/port/open.c
+++ b/src/port/open.c
@@ -122,11 +122,35 @@ pgwin32_open(const char *fileName, int fileFlags,...)
 		return -1;
 	}
 
+	/*
+	 * If caller has set neither O_BINARY nor O_TEXT, then look for what
+	 * the default mode is for this process, then enforce it.  This can
+	 * be done only after opening the file and before switching the file
+	 * mode.
+	 */
+	if ((fileFlags & (O_BINARY | O_TEXT)) == 0)
+	{
+		int		pmode = 0;
+
+		/* only MSVC newer than 2015 support _get_fmode */
+#if (_MSC_VER >= 1900)
+		if (_get_fmode(&pmode) < 0)
+		{
+			/* _get_fmode sets errno */
+			CloseHandle(h);
+			return -1;
+		}
+#else
+		pmode = _fmode;
+#endif
+
+		fileFlags |= pmode;
+	}
+
 	/* _open_osfhandle will, on error, set errno accordingly */
 	if ((fd = _open_osfhandle((intptr_t) h, fileFlags & O_APPEND)) < 0)
 		CloseHandle(h);			/* will not affect errno */
-	else if (fileFlags & (O_TEXT | O_BINARY) &&
-			 _setmode(fd, fileFlags & (O_TEXT | O_BINARY)) < 0)
+	else if (_setmode(fd, fileFlags & (O_TEXT | O_BINARY)) < 0)
 	{
 		_close(fd);
 		return -1;
@@ -138,6 +162,7 @@ pgwin32_open(const char *fileName, int fileFlags,...)
 FILE *
 pgwin32_fopen(const char *fileName, const char *mode)
 {
+	char		fdmode[32];
 	int			openmode = 0;
 	int			fd;
 
@@ -160,7 +185,36 @@ pgwin32_fopen(const char *fileName, const char *mode)
 	fd = pgwin32_open(fileName, openmode);
 	if (fd == -1)
 		return NULL;
-	return _fdopen(fd, mode);
+
+	strcpy(fdmode, mode);
+
+	/*
+	 * Like pgwin32_open, look for the default mode to be used for this
+	 * file descriptor.  Note that it is important to do that again here
+	 * for _fdopen below.
+	 */
+	if ((openmode & (O_BINARY | O_TEXT)) == 0)
+	{
+		int		pmode = 0;
+
+		/* only MSVC newer than 2015 support _get_fmode */
+#if (_MSC_VER >= 1900)
+		if (_get_fmode(&pmode) < 0)
+		{
+			/* get_fmode sets errno */
+			_close(fd);
+			return NULL;
+		}
+#else
+		pmode = _fmode;
+#endif
+
+		snprintf(fdmode, sizeof(fdmode), "%s%s%s", fdmode,
+				 (pmode & O_BINARY) != 0 ? "b" : "",
+				 (pmode & O_TEXT) != 0 ? "t" : "");
+	}
+
+	return _fdopen(fd, fdmode);
 }
 
 #endif
