r-lib / xml2

Bindings to libxml2
https://xml2.r-lib.org/
Other
220 stars 82 forks source link

Trying to read an invalid .xml file makes it so that the file cannot be deleted #376

Open billdenney opened 2 years ago

billdenney commented 2 years ago

When trying to read an invalid .xml file, I cannot delete the. I think that this is because the connection remains open. If important, this happens on Windows (I've not tested other operating systems).

filename <- tempfile(fileext = ".xml")
bad_xml_file <- writeLines("<a>", con = filename)
file.remove(filename)
#> [1] TRUE

filename <- tempfile(fileext = ".xml")
bad_xml_file <- writeLines("<a>", con = filename)
xml2::read_xml(filename)
#> Error in read_xml.character(filename): EndTag: '</' not found [74]
file.remove(filename)
#> Warning in file.remove(filename): cannot remove file 'C:
#> \Users\wdenn\AppData\Local\Temp\RtmpQR65s3\file5e74463b35d8.xml', reason
#> 'Permission denied'
#> [1] FALSE

Created on 2022-10-29 with reprex v2.0.2

billdenney commented 2 years ago

My guess is that after

https://github.com/r-lib/xml2/blob/ab2078976c9ab57116c7c9175632e7d19d45273f/R/xml_parse.R#L109

something like

on.exit({close(con)})

is needed. But, I'm not sure.

TFKentUSDA commented 1 year ago

I have also just run into this problem. at work. I checked it on both my work computer and home computer running several versions of R. In all cases, I'm using xml2_1.3.3. I also verified that this situation appears to be isolated to this package and does not occur if I replace xml2::read_xml(filename) with something else like readxl::read_excel(filename).

Work computer: RStudio 2022.02.1 Build 461 R version 3.5.3 (2019-03-11) R version 3.6.3 (2020-02-29) R version 4.0.3 (2020-10-10) R version 4.1.3 (2022-03-10) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 19044)

Home computer: RStudio 2022.07.2 Build 576 R version 4.2.2 (2022-10-31 ucrt) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 19045)