Golang 读取文件一行内容:使用 bufio.NewScanner 实现 - 示例代码
{"title":"Golang 读取文件一行内容:使用 bufio.NewScanner 实现 - 示例代码","description":"本文介绍如何在 Golang 中使用 bufio.NewScanner 读取文件的一行内容,并提供示例代码演示如何打开文件、创建 Scanner 对象、逐行读取内容以及处理错误。","keywords":"golang, 读取文件, 一行, bufio, NewScanner, 文件读取, 文件操作, 示例代码, golang教程","content":"\u003ccode\u003epackage main\n\nimport (\n\t"bufio"\n\t"fmt"\n\t"os"\n)\n\nfunc main() {\n\t// 打开文件\n\tfile, err := os.Open("example.txt")\n\tif err != nil {\n\t\tfmt.Println("无法打开文件:", err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\t// 创建 Scanner 对象\n\tscanner := bufio.NewScanner(file)\n\n\t// 逐行读取并打印\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfmt.Println(line)\n\t}\n\n\t// 检查是否有错误发生\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Println("读取文件时发生错误:", err)\n\t}\n}\n\u003c/code\u003e\n\n在上述代码中,首先使用 os.Open 函数打开文件,然后使用 bufio.NewScanner 函数创建一个 Scanner 对象。接下来,使用 scanner.Scan 函数来逐行读取文件内容,使用 scanner.Text 函数获取每一行的内容,并将其打印出来。最后,使用 scanner.Err 函数检查是否有错误发生。\n\n请注意,上述代码中的 example.txt 是一个示例文件名,你需要将其替换为实际的文件名。"}
原文地址: https://www.cveoy.top/t/topic/qeSH 著作权归作者所有。请勿转载和采集!