os.read_file(): replace C code with V, return `?string`, handle errors

everywhere
pull/649/head
Alexander Medvednikov 2019-06-26 10:57:13 +02:00
parent b00a47be66
commit 8417fec5dc
3 changed files with 30 additions and 17 deletions

View File

@ -762,13 +762,19 @@ fn new_v(args[]string) *V {
// Location of all vlib files // Location of all vlib files
mut lang_dir = '' mut lang_dir = ''
// First try fetching it from VROOT if it's defined // First try fetching it from VROOT if it's defined
for { // TODO tmp hack for optionals
vroot_path := TmpPath + '/VROOT' vroot_path := TmpPath + '/VROOT'
if os.file_exists(vroot_path) { if os.file_exists(vroot_path) {
vroot := os.read_file(vroot_path).trim_space() mut vroot := os.read_file(vroot_path) or {
break
}
vroot=vroot.trim_space()
if os.dir_exists(vroot) && os.dir_exists(vroot + '/builtin') { if os.dir_exists(vroot) && os.dir_exists(vroot + '/builtin') {
lang_dir = vroot lang_dir = vroot
} }
} }
break
}
// no "~/.vlang/VROOT" file, so the user must be running V for the first // no "~/.vlang/VROOT" file, so the user must be running V for the first
// time. // time.
if lang_dir == '' { if lang_dir == '' {

View File

@ -32,9 +32,13 @@ fn new_scanner(file_path string) *Scanner {
if !os.file_exists(file_path) { if !os.file_exists(file_path) {
panic('"$file_path" doesn\'t exist') panic('"$file_path" doesn\'t exist')
} }
text := os.read_file(file_path) or {
panic('scanner: failed to open "$file_path"')
return &Scanner{}
}
scanner := &Scanner { scanner := &Scanner {
file_path: file_path file_path: file_path
text: os.read_file(file_path) text: text
fmt_out: new_string_builder(1000) fmt_out: new_string_builder(1000)
} }
// println('new scanner "$file_path" txt.len=$scanner.text.len') // println('new scanner "$file_path" txt.len=$scanner.text.len')

33
os/os.v
View File

@ -41,22 +41,25 @@ fn parse_windows_cmd_line(cmd byteptr) {
# os__args = vals; # os__args = vals;
} }
fn C.ftell(fp voidptr) int
// read_file reads the file in `path` and returns the contents. // read_file reads the file in `path` and returns the contents.
// TODO return `?string` pub fn read_file(path string) ?string {
pub fn read_file(path string) string { mut res := ''
res := '' cpath := path.cstr()
# FILE *f = fopen(path.str, "r"); fp := C.fopen(cpath, 'r')
# if (!f) return tos("", 0); if isnil(fp) {
# fseek(f, 0, SEEK_END); return error('failed to open file "$path"')
# long fsize = ftell(f); }
// # fseek(f, 0, SEEK_SET); //same as rewind(f); C.fseek(fp, 0, SEEK_END)
# rewind(f); fsize := C.ftell(fp)
# char *string = malloc(fsize + 1); // C.fseek(fp, 0, SEEK_SET) // same as C.rewind(fp) below
# fread(string, fsize, 1, f); C.rewind(fp)
# fclose(f); mut str := malloc(fsize + 1)
# string[fsize] = 0; C.fread(str, fsize, 1, fp)
// # printf("RFILE= %s\n", string); C.fclose(fp)
# res = tos(string, fsize); str[fsize] = 0
res = tos(str, fsize)
return res return res
} }