主页 > php >
PHP中读取文件的几个方法总结(推荐)(php 读取 文件)
25-01-23
30
在本文中,您将会了解到关于PHP中读取文件的几个方法总结(推荐)的新资讯,同时我们还将为您解释php读取文件的相关在本文中,我们将带你探索PHP中读取文件的几个方法总结(推荐)的奥秘,分析php读取文
在本文中,您将会了解到关于PHP中读取文件的几个方法总结(推荐) 的新资讯,同时我们还将为您解释php 读取 文件 的相关在本文中,我们将带你探索PHP中读取文件的几个方法总结(推荐) 的奥秘,分析php 读取 文件 的特点,并给出一些关于android按行读取文件内容的几个方法、C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结。、golang读取文件的常用方法总结、Go语言中读取命令参数的几种方法总结 的实用技巧。
本文目录一览:
PHP中读取文件的几个方法总结(推荐)(php 读取 文件) 1.fread
string fread ( int $handle , int $length )
fread() 从 handle 指向的文件中读取最多 length 个字节。该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况。
fread() 返回所读取的字符串,如果出错返回 FALSE。
<?php
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");//读取二进制文件时,需要将第二个参数设置成''rb''
//通过filesize获得文件大小,将整个文件一下子读到一个字符串中
$contents = fread($handle, filesize ($filename));
fclose($handle);
?>
如果所要读取的文件不是本地普通文件,而是远程文件或者流文件,就不能用这种方法,因为,filesize不能获得这些文件的大小。此时,你需要通过feof()或者fread()的返回值判断是否已经读取到了文件的末尾。
例如:
<?php
$handle = fopen(''http://www.baidu.com'', ''r'');
$content = '''';
while(!feof($handle)){
$content .= fread($handle, 8080);
}
echo $content;
fclose($handle);
?>
或者:
<?php
$handle = fopen(''http://www.baidu.com'', ''r'');
$content = '''';
while(false != ($a = fread($handle, 8080))){//返回false表示已经读取到文件末尾
$content .= $a;
}
echo $content;
fclose($handle);
?>
2.fgets
string fgets ( int $handle [, int $length ] )
fgets()从 handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。
<?php
$handle = fopen(''./file.txt'', ''r'');
while(!feof($handle)){
echo fgets($handle, 1024);
}
fclose($handle);
?>
Note: length 参数从 PHP 4.2.0 起成为可选项,如果忽略,则行的长度被假定为 1024。从 PHP 4.3 开始,忽略掉 length 将继续从流中读取数据直到行结束。如果文件中的大多数行都大于 8KB,则在脚本中指定最大行的长度在利用资源上更为有效。从 PHP 4.3 开始本函数可以安全用于二进制文件。早期的版本则不行。
3.fgetss
string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )
跟fgets功能一样,但是fgetss会尝试从读取的文本中去掉任何 HTML 和 PHP 标记,可以用可选的第三个参数指定哪些标记不被去掉。
<?php
$handle = fopen(''./file.txt'', ''r'');
while(!feof($handle)){
echo fgetss($handle, 1024, ''<br>'');
}
fclose($handle);
?>
4.file
array file ( string $filename [, int $use_include_path [, resource $context ]] )
将文件内容读入一个数组中,数组的每一项对应文件中的一行,包括换行符在内。不需要行结束符时可以使用 rtrim() 函数过滤换行符。
<?php
$a = file(''./file.txt'');
foreach($a as $line => $content){
echo ''line ''.($line + 1).'':''.$content;
}
?>
5.readfile
int readfile ( string $filename [, bool $use_include_path [, resource $context ]] )
读入一个文件并写入到输出缓冲。返回从文件中读入的字节数。如果出错返回 FALSE 并且除非是以 @readfile() 形式调用,否则会显示错误信息。
<?php
$size = readfile(''./file.txt'');
echo $size;
?>
6.file_get_contents
string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )
将文件读入一个字符串。第三个参数$context可以用来设置一些参数,比如访问远程文件时,设置超时等等。
另外,file_get_contents相对于以上几个函数,性能要好得多,所以应该优先考虑使用file_get_contents。但是readfile貌似比file_get_contents性能好一点(?),因为它不需要调用fopen。
<?php
$ctx = stream_context_create(array(
''http'' => array(
''timeout'' => 1 //设置超时
)
)
);
echo file_get_contents("http://www.baidu.com/", 0, $ctx);
?>
7.fpassthru
int fpassthru ( resource $handle )
将给定的文件指针从当前的位置读取到 EOF 并把结果写到输出缓冲区。
<?php
header("Content-Type:text/html;charset=utf-8");
$handle = fopen(''./test2.php'', ''r'');
fseek($handle, 1024);//将指针定位到1024字节处
fpassthru($handle);
?>
8.parse_ini_file
array parse_ini_file ( string $filename [, bool $process_sections ] )
parse_ini_file() 载入一个由 filename 指定的 ini 文件,并将其中的设置作为一个联合数组返回。如果将最后的 process_sections 参数设为 TRUE,将得到一个多维数组,包括了配置文件中每一节的名称和设置。process_sections 的默认值是 FALSE。
注意:
1. 如果 ini 文件中的值包含任何非字母数字的字符,需要将其括在双引号中(")。
2. 有些保留字不能作为 ini 文件中的键名,包括:null,yes,no,true 和 false。值为 null,no 和 false 等效于 "",值为 yes 和 true 等效于 "1"。字符 {}|&~![()" 也不能用在键名的任何地方,而且这些字符在选项值中有着特殊的意义。
test.ini文件内容:
; This is a sample configuration file
; Comments start with '';'', as in php.ini
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username
test.php内容:
<?php
$config = parse_ini_file(''./test.ini'', ture);
print_r($config);
?>
输出内容:
Array
(
[first_section] => Array
(
[one] => 1
[five] => 5
[animal] => BIRD
)
[second_section] => Array
(
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)
)
几个注意事项:
1. 鼓励在处理二进制文件时使用 b 标志,即使系统并不需要,这样可以使脚本的移植性更好。
2. allow_url_fopen选项激活了 URL 形式的 fopen 封装协议使得可以访问 URL 对象例如文件。默认的封装协议提供用 ftp 和 http 协议来访问远程文件,一些扩展库例如 zlib 可能会注册更多的封装协议。出于安全性考虑,此选项只能在 php.ini 中设置。
3. 如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。
以上这篇PHP中读取文件的几个方法总结(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章: php遍历、读取文件夹中图片并分页显示图片的方法 PHP读取文件的常见几种方法 php fread读取文件注意事项 thinkPHP+PHPExcel实现读取文件日期的方法(含时分秒) php文件操作小结(删除指定文件/获取文件夹下的文件名/读取文件夹下图片名) PHP使用fopen与file_get_contents读取文件实例分享 PHP读取文件内容的五种方式 php从文件夹随机读取文件的方法 php读取文件内容到数组的方法 PHP中读取文件的8种方法和代码实例 PHP按行读取文件时删除换行符的3种方法 php读取文件内容的几种方法详解 PHP读取文件并可支持远程文件的代码分享 php与c 实现按行读取文件实例代码
android按行读取文件内容的几个方法 一、简单版
import java.io.FileInputStream;
void readFileOnLine(){
String strFileName = "Filename.txt";
FileInputStream fis = openFileInput(strFileName);
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
while((strLine = dataIO.readLine()) != null) {
sBuffer.append(strLine + “\n");
}
dataIO.close();
fis.close();
}
二、简洁版
//读取文本文件中的内容
public static String ReadTxtFile(String strFilePath)
{
String path = strFilePath;
String content = ""; //文件内容字符串
//打开文件
File file = new File(path);
//如果path是传递过来的参数,可以做一个非目录的判断
if (file.isDirectory())
{
Log.d("TestFile","The File doesn't not exist.");
}
else
{
try {
InputStream instream = new FileInputStream(file);
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行读取
while (( line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();
}
}
catch (java.io.FileNotFoundException e)
{
Log.d("TestFile","The File doesn't not exist.");
}
catch (IOException e)
{
Log.d("TestFile",e.getMessage());
}
}
return content;
}
三、用于长时间使用的apk,并且有规律性的数据
1,逐行读取文件内容
//首先定义一个数据类型,用于保存读取文件的内容
class WeightRecord {
String timestamp;
float weight;
public WeightRecord(String timestamp,float weight) {
this.timestamp = timestamp;
this.weight = weight;
}
}
//开始读取
private WeightRecord[] readLog() throws Exception {
ArrayList<WeightRecord> result = new ArrayList<WeightRecord>();
File root = Environment.getExternalStorageDirectory();
if (root == null)
throw new Exception("external storage dir not found");
//首先找到文件
File weightLogFile = new File(root,WeightService.LOGFILEPATH);
if (!weightLogFile.exists())
throw new Exception("logfile '"+weightLogFile+"' not found");
if (!weightLogFile.canRead())
throw new Exception("logfile '"+weightLogFile+"' not readable");
long modtime = weightLogFile.lastModified();
if (modtime == lastRecordFileModtime)
return lastLog;
// file exists,is readable,and is recently modified -- reread it.
lastRecordFileModtime = modtime;
// 然后将文件转化成字节流读取
FileReader reader = new FileReader(weightLogFile);
BufferedReader in = new BufferedReader(reader);
long currentTime = -1;
//逐行读取
String line = in.readLine();
while (line != null) {
WeightRecord rec = parseLine(line);
if (rec == null)
Log.e(TAG,"Could not parse line: '"+line+"'");
else if (Long.parseLong(rec.timestamp) < currentTime)
Log.e(TAG,"ignoring '"+line+"' since it's older than prev log line");
else {
Log.i(TAG,"line="+rec);
result.add(rec);
currentTime = Long.parseLong(rec.timestamp);
}
line = in.readLine();
}
in.close();
lastLog = (WeightRecord[]) result.toArray(new WeightRecord[result.size()]);
return lastLog;
}
//解析每一行
private WeightRecord parseLine(String line) {
if (line == null)
return null;
String[] split = line.split("[;]");
if (split.length < 2)
return null;
if (split[0].equals("Date"))
return null;
try {
String timestamp =(split[0]);
float weight = Float.parseFloat(split[1]) ;
return new WeightRecord(timestamp,weight);
}
catch (Exception e) {
Log.e(TAG,"Invalid format in line '"+line+"'");
return null;
}
}
2,保存为文件
public boolean logWeight(Intent batteryChangeIntent) {
Log.i(TAG,"logBattery");
if (batteryChangeIntent == null)
return false;
try {
FileWriter out = null;
if (mWeightLogFile != null) {
try {
out = new FileWriter(mWeightLogFile,true);
}
catch (Exception e) {}
}
if (out == null) {
File root = Environment.getExternalStorageDirectory();
if (root == null)
throw new Exception("external storage dir not found");
mWeightLogFile = new File(root,WeightService.LOGFILEPATH);
boolean fileExists = mWeightLogFile.exists();
if (!fileExists) {
if(!mWeightLogFile.getParentFile().mkdirs()){
Toast.makeText(this,"create file Failed",Toast.LENGTH_SHORT).show();
}
mWeightLogFile.createNewFile();
}
if (!mWeightLogFile.exists()) {
Log.i(TAG,"out = null");
throw new Exception("creation of file '"+mWeightLogFile.toString()+"' Failed");
}
if (!mWeightLogFile.canWrite())
throw new Exception("file '"+mWeightLogFile.toString()+"' is not writable");
out = new FileWriter(mWeightLogFile,true);
if (!fileExists) {
String header = createHeadLine();
out.write(header);
out.write('\n');
}
}
Log.i(TAG,"out != null");
String extras = createBatteryInfoLine(batteryChangeIntent);
out.write(extras);
out.write('\n');
out.flush();
out.close();
return true;
} catch (Exception e) {
Log.e(TAG,e.getMessage(),e);
return false;
}
}
C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结。
C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结。
一、总结
C++/Php/Python/Shell 程序按行读取文件或者控制台(php读取标准输入:$fp = fopen("/dev/stdin", "r");)
1、php读取标准输入:$fp = fopen("/dev/stdin", "r");
二、C++/Php/Python/Shell 程序按行读取文件或者控制台
写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下。方便使用
1. C++
读取文件
1 #include<stdio.h>
2 #include<string .h>
3
4 int main(){
5 const char * in_file = " input_file_name " ;
6 const char * out_file = " output_file_name " ;
7
8 FILE *p_in = fopen(in_file, " r " );
9 if (!p_in){
10 printf(" open file %s failed!!! " , in_file);
11 return -1 ;
12 }
13
14 FILE *p_out = fopen(out_file, " w " );
15 if (!p_in){
16 printf(" open file %s failed!!! " , out_file);
17 if (!p_in){
18 fclose(p_in);
19 }
20 return -1 ;
21 }
22
23 char buf[2048 ];
24 // 按行读取文件内容
25 while (fgets(buf, sizeof (buf), p_in) != NULL) {
26 // 写入到文件
27 fwrite(buf, sizeof (char ), strlen(buf), p_out);
28 }
29
30 fclose(p_in);
31 fclose(p_out);
32 return 0 ;
33 }
View Code
读取标准输入
1 #include<stdio.h>
2
3 int main(){
4 char buf[2048 ];
5
6 gets(buf);
7 printf(" %s\n " , buf);
8
9 return 0 ;
10 }
11
12 /// scanf 遇到空格等字符会结束
13 /// gets 遇到换行符结束
View Code
2. Php
读取文件
1 <?php
2 $filename = "input_file_name";
3
4 $fp = fopen ($filename , "r");
5 if (!$fp ){
6 echo "open file $filename failed\n";
7 exit (1);
8 }
9 else {
10 while (!feof ($fp )){
11 // fgets(file,length) 不指定长度默认为1024字节
12 $buf = fgets ($fp );
13
14 $buf = trim ($buf );
15 if (empty ($buf )){
16 continue ;
17 }
18 else {
19 echo $buf ."\n";
20 }
21 }
22 fclose ($fp );
23 }
24 ?>
View Code
读取标准输入
1 <?php
2 $fp = fopen ("/dev/stdin", "r");
3
4 while ($input = fgets ($fp , 10000)){
5 $input = trim ($input );
6 echo $input ."\n";
7 }
8
9 fclose ($fp );
10 ?>
3. Python
读取文件
1 file = open(" read.py " , " r " )
2 while 1:
3 line = file.readline()
4 if not line:
5 break
6 # line = line
7 line = line.strip() # #移除字符串头尾指定的字符(默认为空格)
8 print line
View Code
读取标准输入
1 # coding=utf-8
2
3 # 如果要在python2的py文件里面写中文,则必须要添加一行声明文件编码的注释,否则python2会默认使用ASCII编码。
4 # 编码申明,写在第一行就好
5 import sys
6
7 input = sys.stdin
8
9 for i in input:
10 # i表示当前的输入行
11
12 i = i.strip()
13 print i
14
15 input.close()
View Code
4. Shell
读取文件
1 #!/bin/bash
2
3 #读取文件, 则直接使用文件名; 读取控制台, 则使用/dev/stdin
4
5 while read line
6 do
7 echo ${line}
8 done < filename
View Code
读取标准输入
1 #!/bin/bash
2
3 while read line
4 do
5 echo ${line}
6 done < /dev/stdin
View Code
golang读取文件的常用方法总结 使用go语言读取文件的各种方式整理。
一次性加载到内存中
// * 整个文件读到内存,适用于文件较小的情况
//每次读取固定字节
//问题容易出现乱码,因为中文和中文符号不占一个字符
func readAllIntoMemory(filename string) (content []byte, err error) {
fp, err := os.Open(filename) // 获取文件指针
if err != nil {
return nil, err
}
defer fp.Close()
fileInfo, err := fp.Stat()
if err != nil {
return nil, err
}
buffer := make([]byte, fileInfo.Size())
_, err = fp.Read(buffer) // 文件内容读取到buffer中
if err != nil {
return nil, err
}
return buffer, nil
}
一次性加载到内存中适用于小文件。 如果文件太大, 内存紧张的情况下, 可以借助缓冲, 分多次读取。
分块读取
// * 一块一块地读取, 即给一个缓冲, 分多次读到缓冲中
//按字节读取,将整个文件读取到缓冲区buffer
func readByBlock(filename string) (content []byte, err error) {
fp, err := os.Open(filename) // 获取文件指针
if err != nil {
return nil, err
}
defer fp.Close()
const bufferSize = 64 // 缓冲大小, 每次读取64个字节
buffer := make([]byte, bufferSize)
for {
// 注意这里要取bytesRead, 否则有问题
bytesRead, err := fp.Read(buffer) // 文件内容读取到buffer中
content = append(content, buffer[:bytesRead]...)
if err != nil {
if err == io.EOF {
err = nil
break
} else {
return nil, err
}
}
}
return
}
有时我们也需要按行处理
按行读
// 逐行读取, 一行是一个[]byte, 多行就是[][]byte
func readByLine(filename string) (lines [][]byte, err error) {
fp, err := os.Open(filename) // 获取文件指针
if err != nil {
return nil, err
}
defer fp.Close()
bufReader := bufio.NewReader(fp)
for {
line, _, err := bufReader.ReadLine() // 按行读
if err != nil {
if err == io.EOF {
err = nil
break
}
} else {
lines = append(lines, line)
}
}
return
}
使用ioutil读取文件的所有内容
func test1() {
bytes,err := ioutil.ReadFile("filetoread.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("total bytes read:",len(bytes))
fmt.Println("string read:",string(bytes))
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
您可能感兴趣的文章: 浅谈Golang是如何读取文件内容的(7种) Golang 实现超大文件读取的两种方法 golang逐行读取文件的操作 GoLang读取文件的10种方法实例
Go语言中读取命令参数的几种方法总结 前言
对于一名初学者来说,想要尽快熟悉 Go 语言特性,所以以操作式的学习方法为主,比如编写一个简单的数学计算器,读取命令行参数,进行数学运算。
本文讲述使用三种方式讲述 Go 语言如何接受命令行参数,并完成一个简单的数学计算,为演示方便,最后的命令行结果大概是这样的:
# input
./calc add 1 2
# output
3
# input
./calc sub 1 2
# out
-1
# input
./calc mul 10 20
# out
200
使用的三种方式是:
内置 os 包读取命令参数
内置 flag 包读取命令参数
cli 框架读取命令参数
0. 已有历史经验
如果你熟悉 Python 、Shell 脚本,你可以比较下:
Python
import sys
args = sys.argv
# args 是一个列表
# 第一个值表示的是 文件名
# 除第一个之外,其他的值是接受的参数
Shell
if [ $# -ne 2 ]; then
echo "Usage: $0 param1 pram2"
exit 1
fi
name=$1
age=$2
echo $name
echo $age
# `$0` 表示文件名
# `$1` 表示第一个参数
# `$2` 表示第二个参数
能看出一些共性,接收参数,一般解析出来都是一个数组(列表、切片), 第一个元素表示的是文件名,剩余的参数表示接收的参数。
好,那么为了实现 “简单数学计算” 这个功能,读取命令行参数:比如 ./calc add 1 2
除文件名之外的第一个元素:解析为 进行数学运算的 操作,比如: add、sub、mul、sqrt
其余参数表示:进行操作的数值
注意: 命令行读取的参数一般为字符串,进行数值计算需要进行数据类型转换
大概思路就是这样。
1. OS 获取命令行参数
os.Args
# 为接受的参数,是一个切片
strconv.Atoi
# 将字符串数值转换为整型
strconv.Itoa
# 将整型转换为字符串
strconv.ParseFloat
# 将字符串数值转换为浮点型
var help = func () {
fmt.Println("Usage for calc tool.")
fmt.Println("====================================================")
fmt.Println("add 1 2,return 3")
fmt.Println("sub 1 2,return -1")
fmt.Println("mul 1 2,return 2")
fmt.Println("sqrt 2,return 1.4142135623730951")
}
func CalcByOs() error {
args := os.Args
if len(args) < 3 || args == nil {
help()
return nil
}
operate := args[1]
switch operate {
case "add":{
rt := 0
number_one,err1 := strconv.Atoi(args[2])
number_two,err2 := strconv.Atoi(args[3])
if err1 == nil && err2 == nil {
rt = number_one + number_two
fmt.Println("Result ",rt)
}
}
case "sub":
{
rt := 0
number_one,err2 := strconv.Atoi(args[3])
if err1 == nil && err2 == nil {
rt += number_one - number_two
fmt.Println("Result ",rt)
}
}
case "mul":
{
rt := 1
number_one,err2 := strconv.Atoi(args[3])
if err1 == nil && err2 == nil {
rt = number_one * number_two
fmt.Println("Result ",rt)
}
}
case "sqrt":
{
rt := float64(0)
if len(args) != 3 {
fmt.Println("Usage: sqrt 2,return 1.4142135623730951")
return nil
}
number_one,err := strconv.ParseFloat(args[2],64)
if err == nil {
rt = math.Sqrt(number_one)
fmt.Println("Result ",rt)
}
}
default:
help()
}
return nil
}
最后的效果大概是:
./calc add 1 2
Result 3
====================
./calc sub 1 2
Result -1
====================
./calc mul 10 20
Result 200
===================
./calc sqrt 2
Result 1.4142135623730951
2. flag 获取命令行参数
flag 包比 os 读取参数更方便。可以自定义传入的参数的类型:比如字符串,整型,浮点型,默认参数设置等
基本的使用方法如下:
var operate string
flag.StringVar(&operate,"o","add","operation for calc")
# 解释
绑定 operate 变量, name="o",value="add",usage="operation for calc"
也可以这样定义为指针变量
var operate := flag.String("o","operation for calc")
同时还可以自定义 flag 类型
所有变量注册之后,调用 flag.Parse() 来解析命令行参数, 如果是绑定变量的方式,直接使用变量进行操作,
如果使用指针变量型,需要 *operate 这样使用。
flag.Args() 表示接收的所有命令行参数集, 也是一个切片
for index,value := range flag.Args {
fmt.Println(index,value)
}
func CalcByFlag() error {
var operation string
var numberone float64
var numbertwo float64
flag.StringVar(&operation,"operation for this tool")
flag.Float64Var(&numberone,"n1","The first number")
flag.Float64Var(&numbertwo,"n2","The second number")
flag.Parse()
fmt.Println(numberone,numbertwo)
if operation == "add" {
rt := numberone + numbertwo
fmt.Println("Result ",rt)
} else if operation == "sub" {
rt := numberone - numbertwo
fmt.Println("Result ",rt)
} else if operation == "mul" {
rt := numberone * numbertwo
fmt.Println("Result ",rt)
} else if operation == "sqrt" {
rt := math.Sqrt(numberone)
fmt.Println("Result ",rt)
} else {
help()
}
return nil
}
最后的结果效果如下:
./calc -o add -n1 1 -n2 2
Result 3
=============================
./calc -o sub -n1 2 -n2 3
Result -1
============================
./calc -o mul -n1 10 -n2 20
Result 200
===========================
./calc -o sqrt -n1 2
Result 1.4142135623730951
3. CLI 框架
cli 是一款业界比较流行的命令行框架。
所以你首先需要安装:
go get github.com/urfave/cli
# 一个简单的示例如下:
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "boom"
app.Usage = "make an explosive entrance"
app.Action = func(c *cli.Context) error {
fmt.Println("boom! I say!")
return nil
}
app.Run(os.Args)
}
好,为实现 “简单数学计算” 的功能,我们应该怎么实现呢?
主要是 使用 框架中的 Flag 功能,对参数进行设置
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "operation,o",Value: "add",Usage: "calc operation",},cli.Float64Flag{
Name: "numberone,n1",Value: 0,Usage: "number one for operation",cli.Float64Flag{
Name: "numbertwo,n2",Usage: "number two for operation",}
能看出,我们使用了三个参数:operation、numberone、numbertwo
同时定义了参数的类型,默认值,以及别名(缩写)
那么在这个框架中如何实现参数的操作呢:主要是重写app.Action 方法
app.Action = func(c *cli.Context) error {
operation := c.String("operation")
numberone := c.Float64("numberone")
numbertwo := c.Float64("numbertwo")
//fmt.Println(operation,numberone,rt)
} else {
help()
}
return nil
}
# 对 operation 参数进行判断,执行的是那种运算,然后编写相应的运算操作
func CalcByCli(){
app := cli.NewApp()
app.Name = "calc with go"
app.Usage = "calc tool operate by go"
app.Version = "0.1.0"
app.Flags = [] cli.Flag {
cli.StringFlag{
Name: "operation,cli.Float64Flag{
Name: "numberone,cli.Float64Flag{
Name: "numbertwo,}
app.Action = func(c *cli.Context) error {
operation := c.String("operation")
numberone := c.Float64("numberone")
numbertwo := c.Float64("numbertwo")
//fmt.Println(operation,numbertwo)
if operation == "add" {
rt := numberone + numbertwo
fmt.Println("Result ",rt)
} else if operation == "sub" {
rt := numberone - numbertwo
fmt.Println("Result ",rt)
} else if operation == "mul" {
rt := numberone * numbertwo
fmt.Println("Result ",rt)
} else if operation == "sqrt" {
rt := math.Sqrt(numberone)
fmt.Println("Result ",rt)
} else {
help()
}
return nil
}
app.Run(os.Args)
}
调用这个函数的最终效果如下:
./calc -o add --n1 12 --n2 12
Result 24
===================================
./calc -o sub --n1 100 --n2 200
Result -100
===================================
./calc -o mul --n1 10 --n2 20
Result 200
===================================
./calc -o sqrt --n1 2
Result 1.4142135623730951
4 其他
知道如何读取命令行参数,就可以实现一些更有意思的事。
比如网上有许多免费的 API 接口,比如查询天气,查询农历的API 接口。
还有一些查询接口,比如有道云翻译接口,你可以实现翻译的功能。
或者扇贝的接口,实现查询单词的功能。
再比如一些音乐接口,实现音乐信息查询。
不一一列了。
下面实现一个调用免费的查询天气的接口实现命令行查询天气。
GO 如何进行 HTTP 访问?内置的 net/http 可以实现
一个简易的GET 操作如下:
func Requests(url string) (string,error) {
response,err := http.Get(url)
if err != nil {
return "",err
}
defer response.Body.Close()
body,_ := IoUtil.ReadAll(response.Body)
return string(body),nil
}
免费的 API URL 如下:
http://www.sojson.com/open/api/weather/json.shtml?city=北京
返回的结果是一个Json 格式的数据
{
"status": 200,"data": {
"wendu": "29","ganmao": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。","forecast": [
{
"fengxiang": "南风","fengli": "3-4级","high": "高温 32℃","type": "多云","low": "低温 17℃","date": "16日星期二"
},{
"fengxiang": "南风","fengli": "微风级","high": "高温 34℃","type": "晴","low": "低温 19℃","date": "17日星期三"
},"high": "高温 35℃","low": "低温 22℃","date": "18日星期四"
},"date": "19日星期五"
},"low": "低温 21℃","date": "20日星期六"
}
],"yesterday": {
"fl": "微风","fx": "南风","high": "高温 28℃","low": "低温 15℃","date": "15日星期一"
},"aqi": "72","city": "北京"
},"message": "OK"
}
所以我们的任务就是传入 “城市” 的名称,再对返回的 Json 数据解析。
package main
import (
"fmt"
"os"
"encoding/json"
"github.com/urfave/cli"
"net/http"
"io/IoUtil"
//"github.com/modood/table"
)
type Response struct {
Status int `json:"status"`
CityName string `json:"city"`
Data Data `json:"data"`
Date string `json:"date"`
Message string `json:"message"`
Count int `json:"count"`
}
type Data struct {
ShiDu string `json:"shidu"`
Quality string `json:"quality"`
Ganmao string `json:"ganmao"`
Yesterday Day `json:"yesterday"`
Forecast []Day `json:"forecast"`
}
type Day struct {
Date string `json:"date"`
Sunrise string `json:"sunrise"`
High string `json:"high"`
Low string `json:"low"`
Sunset string `json:"sunset"`
Aqi float32 `json:"aqi"`
Fx string `json:"fx"`
Fl string `json:"fl"`
Type string `json:"type"`
Notice string `json:"notice"`
}
func main() {
const apiURL = "http://www.sojson.com/open/api/weather/json.shtml?city="
app := cli.NewApp()
app.Name = "weather-cli"
app.Usage = "天气预报小程序"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "city,c",Value: "上海",Usage: "城市中文名",cli.StringFlag{
Name: "day,d",Value: "今天",Usage: "可选: 今天,昨天,预测",cli.StringFlag{
Name: "Author,r",Value: "xiewei",Usage: "Author name",}
app.Action = func(c *cli.Context) error {
city := c.String("city")
day := c.String("day")
var body,err = Requests(apiURL + city)
if err != nil {
fmt.Printf("err was %v",err)
return nil
}
var r Response
err = json.Unmarshal([]byte(body),&r)
if err != nil {
fmt.Printf("\nError message: %v",err)
return nil
}
if r.Status != 200 {
fmt.Printf("获取天气API出现错误,%s",r.Message)
return nil
}
Print(day,r)
return nil
}
app.Run(os.Args)
}
func Print(day string,r Response) {
fmt.Println("城市:",r.CityName)
if day == "今天" {
fmt.Println("湿度:",r.Data.ShiDu)
fmt.Println("空气质量:",r.Data.Quality)
fmt.Println("温馨提示:",r.Data.Ganmao)
} else if day == "昨天" {
fmt.Println("日期:",r.Data.Yesterday.Date)
fmt.Println("温度:",r.Data.Yesterday.Low,r.Data.Yesterday.High)
fmt.Println("风量:",r.Data.Yesterday.Fx,r.Data.Yesterday.Fl)
fmt.Println("天气:",r.Data.Yesterday.Type)
fmt.Println("温馨提示:",r.Data.Yesterday.Notice)
} else if day == "预测" {
fmt.Println("====================================")
for _,item := range r.Data.Forecast {
fmt.Println("日期:",item.Date)
fmt.Println("温度:",item.Low,item.High)
fmt.Println("风量:",item.Fx,item.Fl)
fmt.Println("天气:",item.Type)
fmt.Println("温馨提示:",item.Notice)
fmt.Println("====================================")
}
} else {
fmt.Println("...")
}
}
func Requests(url string) (string,error) {
response,err := http.Get(url)
if err != nil {
return "",err
}
defer response.Body.Close()
body,_ := IoUtil.ReadAll(response.Body)
return string(body),nil
}
最终的效果大概如下:
./weather -c 上海
城市: 上海
湿度: 80%
空气质量: 轻度污染
温馨提示: 儿童、老年人及心脏、呼吸系统疾病患者人群应减少长时间或高强度户外锻炼
================================
./weaather -c 上海 -d 昨天
城市: 上海
日期: 28日星期二
温度: 低温 12.0℃ 高温 19.0℃
风量: 西南风 <3级
天气: 小雨
温馨提示: 雾蒙蒙的雨天,最喜欢一个人听音乐
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程小技巧的支持。
今天关于PHP中读取文件的几个方法总结(推荐) 和php 读取 文件 的分享就到这里,希望大家有所收获,若想了解更多关于android按行读取文件内容的几个方法、C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结。、golang读取文件的常用方法总结、Go语言中读取命令参数的几种方法总结 等相关知识,可以在本站进行查询。