Oleg
Oleg

Reputation: 1559

Write at certain byte/position in file Ocaml

Is there any equivalent to seekp() in OCaml ? I need to write chars in a file at certain offsets.

Upvotes: 0

Views: 121

Answers (2)

V. Michel
V. Michel

Reputation: 1619

An utop example, to write a character ('A') at a certain position inside a file (Test.data):

#use "topfind";;
#require "unix";;
open Unix;;

let fd=openfile "Test.data" [O_WRONLY; O_TRUNC; O_CREAT] 0o666;;

let nbBytes=lseek fd 12 Unix.SEEK_SET;;      
if nbBytes<>12 then failwith "Unix.lseek";;

let nbChars= write fd "A" 0 1;;     
if nbChars<>1 then failwith "Unix.write";;
close fd;;

od -cv Test.data

0000000  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0   A

Explanations:

  • SEEK_SET indicates positions relative to the beginning of the file.
  • The result of lseek is offset from the beginning of the file.
  • To rewind the file you can use : lseek fd 0 Unix.SEEK_SET.
  • To read the second character of the file, you have to do ( before reading):lseek fd 1 Unix.SEEK_SET.

Upvotes: 2

kne
kne

Reputation: 1418

Possibly you are looking for Unix.lseek, though I am unfamiliar with the exact semantics.

Upvotes: 1

Related Questions