Skip to content

Instantly share code, notes, and snippets.

@APTy
Created February 7, 2017 23:24
Show Gist options
  • Save APTy/d307797abee9e5de0184ae49722b6ac4 to your computer and use it in GitHub Desktop.
Save APTy/d307797abee9e5de0184ae49722b6ac4 to your computer and use it in GitHub Desktop.
cgo
// A simple cgo example for writing to a file.
package main
// #include <stdlib.h>
// #include <stdio.h>
import "C"
import (
"errors"
"fmt"
"unsafe"
)
// FileReadWrite means we can read and/or write to the file.
const FileReadWrite = "w+"
// ErrWrite indicates a write did not complete successfully.
var ErrWrite = errors.New("failed to write")
// File is any file in the file system.
type File struct {
fp *C.FILE
name string
}
// Open returns a new File for writing.
func Open(filename string) (*File, error) {
cFilename := C.CString(filename)
cMode := C.CString(FileReadWrite)
defer C.free(unsafe.Pointer(cFilename))
defer C.free(unsafe.Pointer(cMode))
fp, err := C.fopen(cFilename, cMode)
if err != nil {
return nil, err
}
return &File{
fp: fp,
name: filename,
}, nil
}
// Close frees up the File's memory and closes the file descriptor.
func (f *File) Close() {
C.fclose(f.fp)
}
// Write prints a string into the file.
func (f *File) Write(content string) error {
size := C.size_t(len(content))
cContent := unsafe.Pointer(C.CString(content))
defer C.free(cContent)
n := C.fwrite(cContent, size, 1, f.fp)
if n == 0 {
return ErrWrite
}
return nil
}
func main() {
f, err := Open("tmp.txt")
if err != nil {
fmt.Printf("failed to open file: %s", err)
}
defer f.Close()
f.Write("hello\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment