Friday, 17 July 2020

Working with File system in Go

Package os contains useful functions for working with file system.

os - The Go Programming Language



Open() 

  • opens the named file for reading (O_RDONLY mode).


OpenFile() 
  • opens file in a specified mode set via flag e.g.  O_RDWR or O_WRONLY.

Create() 
  • creates or truncates the named file
  • If the file already exists, it is truncated. 
  • If the file does not exist, it is created. 
  • Methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR.

Truncate() function:
  • requires file to be opened in mode which allows writing into it.
  • if specified size is 0 deletes the content of the file and sets its size to 0.

Writing to files


Go by Example: Writing Files

Without buffering:


f, err := os.Create("/tmp/test.txt")
if err != nil {
panic(err)
}
defer f.Close()
f.WriteString("some text!\n")


WriteString() under the hood calls system function write():

r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))

write() belongs to the group of Unix unbuffered file I/O functions (together with openclosereadlseek...).

From FILE I/O:
They are part of the POSIX standard for UNIX programming, not part of ANSI C. Unlike the standard I/O routines provided by ANSI C (such as fscanf and fprintf which store the data they read in buffers) these functions are unbuffered I/O. They invoke a system call in the kernel, and will be called by the standard ANSI C function calls in the UNIX environment.

With buffering:


f, err := os.Create("/tmp/test.txt")
if err != nil {
panic(err)
}
defer f.Close()
w := bufio.NewWriter(f)
w.WriteString("some text!\n")
w.Flush()


1 comment:

micheal pan said...

BE SMART AND BECOME RICH IN LESS THAN 3DAYS....It all depends on how fast 
you can be to get the new PROGRAMMED blank ATM card that is capable of
hacking into any ATM machine,anywhere in the world. I got to know about 
this BLANK ATM CARD when I was searching for job online about a month 
ago..It has really changed my life for good and now I can say I'm rich and 
I can never be poor again. The least money I get in a day with it is about 
$50,000.(fifty thousand USD) Every now and then I keeping pumping money 
into my account. Though is illegal,there is no risk of being caught 
,because it has been programmed in such a way that it is not traceable,it 
also has a technique that makes it impossible for the CCTVs to detect 
you..For details on how to get yours today, email the hackers on : (
atmmachinehackers1@gmail.com ). Tell your 
loved once too, and start to live large. That's the simple testimony of how 
my life changed for good...Love you all ...the email address again is ;
atmmachinehackers1@gmail.com