mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
os: implement File.seek/2 and File.tell/0
This commit is contained in:
@@ -16,6 +16,7 @@ struct FileInfo {
|
||||
fn C.fseeko(&C.FILE, u64, int) int
|
||||
|
||||
fn C._fseeki64(&C.FILE, u64, int) int
|
||||
fn C._ftelli64(&C.FILE) i64
|
||||
|
||||
fn C.getc(&C.FILE) int
|
||||
|
||||
@@ -727,3 +728,60 @@ pub fn (mut f File) write_raw_at<T>(t &T, pos u64) ? {
|
||||
return error_with_code('incomplete struct write', nbytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub enum SeekMode {
|
||||
start
|
||||
current
|
||||
end
|
||||
}
|
||||
|
||||
// seek moves the file cursor (if any) associated with a file
|
||||
// to a new location, offset `pos` bytes from the origin. The origin
|
||||
// is dependent on the `mode` and can be:
|
||||
// .start -> the origin is the start of the file
|
||||
// .current -> the current position/cursor in the file
|
||||
// .end -> the end of the file
|
||||
// If the file is not seek-able, or an error occures, the error will
|
||||
// be returned to the caller.
|
||||
// A successful call to the fseek() function clears the end-of-file
|
||||
// indicator for the file.
|
||||
pub fn (mut f File) seek(pos i64, mode SeekMode) ? {
|
||||
if !f.is_opened {
|
||||
return error_file_not_opened()
|
||||
}
|
||||
whence := int(mode)
|
||||
mut res := 0
|
||||
$if x64 {
|
||||
$if windows {
|
||||
res = C._fseeki64(f.cfile, pos, whence)
|
||||
} $else {
|
||||
res = C.fseeko(f.cfile, pos, whence)
|
||||
}
|
||||
}
|
||||
$if x32 {
|
||||
res = C.fseek(f.cfile, pos, whence)
|
||||
}
|
||||
if res == -1 {
|
||||
return error(posix_get_error_msg(C.errno))
|
||||
}
|
||||
}
|
||||
|
||||
// tell will return the current offset of the file cursor measured from
|
||||
// the start of the file, in bytes. It is complementary to seek, i.e.
|
||||
// you can use the return value as the `pos` parameter to .seek( pos, .start ),
|
||||
// so that your next read will happen from the same place.
|
||||
pub fn (f &File) tell() ?i64 {
|
||||
if !f.is_opened {
|
||||
return error_file_not_opened()
|
||||
}
|
||||
mut pos := i64(0)
|
||||
$if windows && x64 {
|
||||
pos = C._ftelli64(f.cfile)
|
||||
} $else {
|
||||
pos = C.ftell(f.cfile)
|
||||
}
|
||||
if pos == -1 {
|
||||
return error(posix_get_error_msg(C.errno))
|
||||
}
|
||||
return pos
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user