Restore stdin

Hi forum,

I tried to use freopen() with readLine() in Ubuntu 20.04 Linux, and failed to restore the stdin.
I then tried to use dup2() with readLine() but the 3rd readLine() call inside readFile() below didn't prompt for input.

How can I restore stdin? So I don't need to go to fopen() and fgets() for line oriented text file io.

Thanks

//main.swift
import Foundation

//write text file line by line
func writeFile(name: String) {
    print(#line) //
    guard let fp = fopen(name, "w") else {
        perror(name)
        exit(1)
    }
    let fd = dup(1)
    dup2(fileno(fp), 1)
    fclose(fp)
    print("hello1")
    print("hello2")
    print("hello3")
    fflush(stdout)
    dup2(fd, 1)
    close(fd)
    print(#line) //
}

//read text file line by line
func readFile(name: String) {
    print(#line) //
    var line = readLine()
    guard let fp = fopen(name, "r") else {
        perror(name)
        exit(1)
    }

    let fd = dup(0)
    dup2(fileno(fp), 0)
    fclose(fp)
    while let line = readLine() {
        print(#line, line)
    }
    dup2(fd, 0)
    close(fd)
    line = readLine() // Not prompt for input !
    print(#line) //
}

var file = "/home/ljh/Documents/hello/hello.txt"
var line: String? = "hello"
writeFile(name: file)
readFile(name: file)

/*
$ swift main.swift
5
19
24
hello
35 hello1
35 hello2
35 hello3
40

$
 */
Terms of Service

Privacy Policy

Cookie Policy