Created
July 17, 2015 11:05
-
-
Save rominirani/b6375585242c390c60e8 to your computer and use it in GitHub Desktop.
Go Course : Exercise 17
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Manipulate a text file.Search for 'word' in this text file and replace it with 'inserted word'. Write the contents | |
back into the original file | |
*/ | |
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"os" | |
) | |
func check(e error) { | |
if e != nil { | |
log.Fatal(e) | |
} | |
} | |
func main() { | |
//Check for program arguments | |
args := os.Args | |
numArgs := len(args) | |
if numArgs != 2 { | |
log.Fatal("You must provide the text file name") | |
} | |
filename := args[1] | |
file, err := ioutil.ReadFile(filename) | |
check(err) | |
output := bytes.Replace(file, []byte("word"), []byte("inserted word"), -1) | |
err = ioutil.WriteFile(filename, output, 0666) | |
check(err) | |
fmt.Println("File has been modified successfully.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment