Search…
Files
A File in V is an abstraction of any file object accessible by the program and is closely associated with os library.

Reading Files

Reading a file is an important task to tackle several different problems in computer science. In order to accomplish this task you can use the V native library os as described below:
1
import os
2
3
fn main() {
4
mut fp := flag.new_flag_parser(os.args)
5
generator := fp.string('generator', '', 'generator name')
6
method := fp.string('method', '', 'generator method name')
7
path := './data/$generator/$method'
8
9
if os.file_exists(path) {
10
print_generator_sample(path)
11
} else {
12
println('File does not exist')
13
return
14
}
15
}
16
17
fn print_generator_sample(path string) {
18
contents := os.read_file(path.trim_space()) or {
19
println('Failed to open $path')
20
return
21
}
22
23
lines := contents.split_into_lines()
24
length := lines.len
25
26
print_random_element(lines, length)
27
}
28
29
fn print_random_element(lines []string, length int) {
30
rand.seed(time.now().uni)
31
32
println(lines[rand.next(length-1)])
33
}
Copied!

Writing files

Writing files in V is similar to read files.
1
import os
2
3
fn main() {
4
path := './data/file.txt'
5
text := 'Full text description.'
6
7
if contents := os.write_file(path, text) or {
8
println('Failed while creating file')
9
return
10
}
11
12
content_lines = read_file(path)
13
print(content_lines)
14
}
15
16
fn read_file(path string) {
17
contents := os.read_file(path.trim_space()) or {
18
println('Failed to open $path')
19
return
20
}
21
22
return contents.split_into_lines()
23
}
Copied!

Exercises

  1. 1.
    Write a V program to create a new file with content.
  2. 2.
    Write a V program to read 2 different files and display their content.
  3. 3.
    Read how the os library works in V and understand how you could use it.
  4. 4.
    Encode a nested json string and write a new file with the result.
Last modified 2yr ago