os: fix os.open_file/3 wb mode creation of text files containing crlf on Windows (#20101)

This commit is contained in:
Dmitriy Mihaylenko 2023-12-08 21:52:52 +02:00 committed by GitHub
parent 4d1eb5f215
commit 75c0c92759
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 2 deletions

View File

@ -109,8 +109,7 @@ pub fn open_file(path string, mode string, options ...int) !File {
if fd == -1 {
return error(posix_get_error_msg(C.errno))
}
fdopen_mode := mode.replace('b', '')
cfile := C.fdopen(fd, &char(fdopen_mode.str))
cfile := C.fdopen(fd, &char(mode.str))
if isnil(cfile) {
return error('Failed to open or create file "${path}"')
}

View File

@ -450,3 +450,30 @@ fn test_open_file_on_chinese_windows() {
assert os.file_size('.txt') == 2
}
}
fn test_open_file_crlf_binary_mode() {
teststr := 'hello\r\n'
fname := 'text.txt'
mut wfile := os.open_file(fname, 'w', 0o666)!
wfile.write_string(teststr)!
wfile.close()
mut fcont_w := os.read_file(fname)!
os.rm(fname) or {}
mut wbfile := os.open_file(fname, 'wb', 0o666)!
wbfile.write_string(teststr)!
wbfile.close()
mut fcont_wb := os.read_file(fname)!
os.rm(fname) or {}
$if windows {
assert fcont_w != teststr
}
assert fcont_wb == teststr
}