Skip to content

Commit 61b1924

Browse files
authored
Rollup merge of rust-lang#113876 - darklyspaced:master, r=cuviper
fix docs & example for `std::os::unix::prelude::FileExt::write_at` Changelog: * used `File::create` instead of `File::read` to get a writeable file * explicity mentioned the bug with `pwrite64` in docs Unfortunately, I don't think that there is really much we can do about this since the feature has already been stabilised. We could potentially add a clippy lint warning people on Linux that using `write_at` with the `O_APPEND` flag does not exhibit the behaviour that they would have assumed. fixes rust-lang#113627
2 parents d6d29e4 + 7d17a26 commit 61b1924

File tree

1 file changed

+30
-1
lines changed
  • library/std/src/os/unix

1 file changed

+30
-1
lines changed

library/std/src/os/unix/fs.rs

+30-1
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,36 @@ pub trait FileExt {
149149
/// Note that similar to [`File::write`], it is not an error to return a
150150
/// short write.
151151
///
152+
/// # Bug
153+
/// On some systems, `write_at` utilises [`pwrite64`] to write to files.
154+
/// However, this syscall has a [bug] where files opened with the `O_APPEND`
155+
/// flag fail to respect the offset parameter, always appending to the end
156+
/// of the file instead.
157+
///
158+
/// It is possible to inadvertantly set this flag, like in the example below.
159+
/// Therefore, it is important to be vigilant while changing options to mitigate
160+
/// unexpected behaviour.
161+
///
162+
/// ```no_run
163+
/// use std::fs::File;
164+
/// use std::io;
165+
/// use std::os::unix::prelude::FileExt;
166+
///
167+
/// fn main() -> io::Result<()> {
168+
/// // Open a file with the append option (sets the `O_APPEND` flag)
169+
/// let file = File::options().append(true).open("foo.txt")?;
170+
///
171+
/// // We attempt to write at offset 10; instead appended to EOF
172+
/// file.write_at(b"sushi", 10)?;
173+
///
174+
/// // foo.txt is 5 bytes long instead of 15
175+
/// Ok(())
176+
/// }
177+
/// ```
178+
///
152179
/// [`File::write`]: fs::File::write
180+
/// [`pwrite64`]: https://man7.org/linux/man-pages/man2/pwrite.2.html
181+
/// [bug]: https://man7.org/linux/man-pages/man2/pwrite.2.html#BUGS
153182
///
154183
/// # Examples
155184
///
@@ -159,7 +188,7 @@ pub trait FileExt {
159188
/// use std::os::unix::prelude::FileExt;
160189
///
161190
/// fn main() -> io::Result<()> {
162-
/// let file = File::open("foo.txt")?;
191+
/// let file = File::create("foo.txt")?;
163192
///
164193
/// // We now write at the offset 10.
165194
/// file.write_at(b"sushi", 10)?;

0 commit comments

Comments
 (0)