@@ -1069,34 +1069,38 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> {
10691069 let mut wfd = mem::zeroed();
10701070 let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd);
10711071
1072- // The status `ERROR_FILE_NOT_FOUND` is returned by the `FindFirstFileW` function
1073- // if no matching files can be found, but not necessarily that the path to find the
1074- // files in does not exist.
1075- //
1076- // Hence, a check for whether the path to search in exists is added when the last
1077- // os error returned by Windows is `ERROR_FILE_NOT_FOUND` to handle this scenario.
1078- // If that is the case, an empty `ReadDir` iterator is returned as it returns `None`
1079- // in the initial `.next()` invocation because `ERROR_NO_MORE_FILES` would have been
1080- // returned by the `FindNextFileW` function.
1081- //
1082- // See issue #120040: https://github.com/rust-lang/rust/issues/120040.
1083- let last_error = Error::last_os_error();
1084- if last_error.raw_os_error().unwrap() == c::ERROR_FILE_NOT_FOUND as i32 && p.exists() {
1085- return Ok(ReadDir {
1086- handle: FindNextFileHandle(find_handle),
1087- root: Arc::new(root),
1088- first: None,
1089- });
1090- }
1091-
10921072 if find_handle != c::INVALID_HANDLE_VALUE {
10931073 Ok(ReadDir {
10941074 handle: FindNextFileHandle(find_handle),
10951075 root: Arc::new(root),
10961076 first: Some(wfd),
10971077 })
10981078 } else {
1099- Err(last_error)
1079+ // The status `ERROR_FILE_NOT_FOUND` is returned by the `FindFirstFileW` function
1080+ // if no matching files can be found, but not necessarily that the path to find the
1081+ // files in does not exist.
1082+ //
1083+ // Hence, a check for whether the path to search in exists is added when the last
1084+ // os error returned by Windows is `ERROR_FILE_NOT_FOUND` to handle this scenario.
1085+ // If that is the case, an empty `ReadDir` iterator is returned as it returns `None`
1086+ // in the initial `.next()` invocation because `ERROR_NO_MORE_FILES` would have been
1087+ // returned by the `FindNextFileW` function.
1088+ //
1089+ // See issue #120040: https://github.com/rust-lang/rust/issues/120040.
1090+ let last_error = api::get_last_error();
1091+ if last_error.code == c::ERROR_FILE_NOT_FOUND {
1092+ return Ok(ReadDir {
1093+ handle: FindNextFileHandle(find_handle),
1094+ root: Arc::new(root),
1095+ first: None,
1096+ });
1097+ }
1098+
1099+ // Just return the error constructed from the raw OS error if the above is not the case.
1100+ //
1101+ // Note: `ERROR_PATH_NOT_FOUND` would have been returned by the `FindFirstFileW` function
1102+ // when the path to search in does not exist in the first place.
1103+ Err(Error::from_raw_os_error(last_error.code as i32));
11001104 }
11011105 }
11021106}
0 commit comments