写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下。方便使用
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 ?>
View Code
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
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/2070.html