fs::File::seek() false positive?

In below code, a file is opened in append-only mode. Later when seeked, it does not fail with "seek failed" message. Is this expected ? Feels like it should return Err, given that the file is opened in append-only mode.

use std::{
    fs, io,
    io::{Seek, Write},

fn main() {
    let mut dir = std::env::temp_dir();
    let file = dir.as_path().to_str().unwrap();

    let p = path::Path::new(file);
    let mut opts = fs::OpenOptions::new();
    let mut fd = opts.append(true).create_new(true).open(p).unwrap();

    fd.write("hello world".as_bytes()).expect("write failed");
    fd.seek(io::SeekFrom::Start(1)).expect("seek failed");
    fd.write("i world".as_bytes()).expect("write failed");

    let txt = fs::read(file).expect("read failed");
    assert_eq!(std::str::from_utf8(&txt).unwrap(), "hello worldi world");

I don't know about other platforms, but this is the "expected" behavior in Linux:

#include <stdio.h>
#include <stdlib.h>

#define my_write(str_literal, file) do { \
    fwrite(str_literal, 1, sizeof(str_literal) - 1, file); \
    if (ferror(file)) { \
        perror("fwrite"); \
        exit(EXIT_FAILURE); \
    } \
} while (0)

int main (int argc, char const * argv[])
    FILE * file = fopen("bar.txt", "a");
    if (file == NULL) {
        return EXIT_FAILURE;
    my_write("hello world", file);
    if (fseek(file, 1, SEEK_SET) == -1) {
        return EXIT_FAILURE;
    my_write("i world", file);
    return EXIT_SUCCESS;
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.