[golang] golang文件读写 os.OpenFile(fileName,os.O_APPEND|os.O_WRONLY,os.ModeAppend)

本文详细介绍了Golang中使用os包进行文件读写的多种方法,包括如何利用os.OpenFile进行文件的创建、读写、追加及删除操作,同时解释了不同标志位的作用及其组合使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[golang] golang文件读写 os.OpenFile(fileName,os.O_APPEND|os.O_WRONLY,os.ModeAppend)

读写文件要用到的OS包

func OpenFile(name string, flag int, perm FileMode) (*File, error) 

该方法第一个参数为文件路径,第二个参数控制文件的打开方式,第三个参数控制文件模式

可用的打开方式有

// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
const (
    // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    // 只读模式
    O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    // 只写模式
    O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    // 可读可写
    O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    // The remaining values may be or'ed in to control behavior.
    // 追加内容
    O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    // 创建文件,如果文件不存在
    O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    // 与创建文件一同使用,文件必须存在
    O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    // 打开一个同步的文件流
    O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    // 如果可能,打开时缩短文件
    O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
)

打开模式

// The defined file mode bits are the most significant bits of the FileMode.
// The nine least-significant bits are the standard Unix rwxrwxrwx permissions.
// The values of these bits should be considered part of the public API and
// may be used in wire protocols or disk representations: they must not be
// changed, although new bits might be added.
const (
    // The single letters are the abbreviations
    // used by the String method's formatting.
    // 文件夹模式
    ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
    // 追加模式
    ModeAppend                                     // a: append-only
    // 单独使用
    ModeExclusive                                  // l: exclusive use
    // 临时文件
    ModeTemporary                                  // T: temporary file; Plan 9 only
    // 象征性的关联
    ModeSymlink                                    // L: symbolic link
    // 设备文件
    ModeDevice                                     // D: device file
    // 命名管道
    ModeNamedPipe                                  // p: named pipe (FIFO)
    // Unix 主机 socket
    ModeSocket                                     // S: Unix domain socket
    // 设置uid
    ModeSetuid                                     // u: setuid
    // 设置gid
    ModeSetgid                                     // g: setgid
    // UNIX 字符串设备,当设备模式是设置unix
    ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
    // 粘性的
    ModeSticky                                     // t: sticky
    // 非常规文件;对该文件一无所知
    ModeIrregular                                  // ?: non-regular file; nothing else is known about this file

    // bit位遮盖,不变的文件设置为none
    // Mask for the type bits. For regular files, none will be set.
    ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice | ModeCharDevice | ModeIrregular
    // 权限位
    ModePerm FileMode = 0777 // Unix permission bits
)

创建一个文件并追加内容

package main

import (
    "os"
)
func main() {
    fname := "/tmp/t.txt"
    f, err := os.OpenFile(fname, os.O_CREATE|os.O_RDWR|os.O_APPEND, os.ModeAppend|os.ModePerm)
    if err != nil {
        fmt.Println(err)
    }
    f.WriteString("test")
    f.Close()
}

删除文件

os.Remove(fname)

创建目录

dname :="/tmp/d"

os.Mkdir(dname,os.ModeDir|os.ModePerm)

创建完整目录路径,即中间目录不存在的话也一起创建

os.MkdirAll(dname,os.ModeDir|os.ModePerm)

golang os.OpenFile几种常用模式

os.O_WRONLY | os.O_CREATE | O_EXCL           【如果已经存在,则失败】

os.O_WRONLY | os.O_CREATE                         【如果已经存在,会覆盖写,不会清空原来的文件,而是从头直接覆盖写】

os.O_WRONLY | os.O_CREATE | os.O_APPEND  【如果已经存在,则在尾部添加写】

如果想要在已经存在的文件尾部添加写入内容,可以使用以下方法中的任意一种: 1. 使用Python的open函数打开文件时,可以使用"r+"模式来同时进行读写操作。例如: ``` with open("filename.txt", "r+") as file: file.seek(0, os.SEEK_END) file.write("content to append") ``` 这样就可以在文件尾部添加写入内容了。 2. 使用os模块的open函数打开文件时,可以通过传递参数os.O_WRONLY | os.O_CREATE | os.O_APPEND来在已存在文件的尾部添加写入内容。例如: ``` import os with os.open("filename.txt", os.O_WRONLY | os.O_CREATE | os.O_APPEND) as file: file.write("content to append") ``` 这样也可以在文件尾部添加写入内容。 需要注意的是,上述代码中的"filename.txt"应该替换为你实际要操作的文件名。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [[golang] golang文件读写 os.OpenFile(fileName,os.O_APPEND|os.O_WRONLY,os.ModeAppend)](https://blog.csdn.net/dodod2012/article/details/117706665)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [xml_AOI -1.7z](https://download.csdn.net/download/qq_39146438/16299444)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值