大佬教程收集整理的这篇文章主要介绍了C++/Php/Python/Shell 程序按行读取文件或者控制台的实现,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下。方便使用
1. C++
读取文件
#include<stdio.h> #include<String.h> int main(){ const char* in_file = "input_file_name"; const char* out_file = "output_file_name"; FILE *p_in = fopen(in_file,"r"); if(!p_in){ printf("open file %s Failed!!!",in_filE); return -1; } FILE *p_out = fopen(out_file,"w"); if(!p_in){ printf("open file %s Failed!!!",out_filE); if(!p_in){ fclose(p_in); } return -1; } char buf[2048]; //按行读取文件内容 while(fgets(buf,sizeof(buf),p_in) != NULL) { //写入到文件 fwrite(buf,sizeof(char),strlen(buf),p_out); } fclose(p_in); fclose(p_out); return 0; }
读取标准输入
#include<stdio.h> int main(){ char buf[2048]; gets(buf); printf("%s\n",buf); return 0; } /// scanf 遇到空格等字符会结束 /// gets 遇到换行符结束
2. PHP
读取文件
<?PHP $filename = "input_file_name"; $fp = fopen($filename,"r"); if(!$fp){ echo "open file $filename Failed\n"; exit(1); } else{ while(!feof($fp)){ //fgets(file,length) 不指定长度默认为1024字节 $buf = fgets($fp); $buf = trim($buf); if(empty($buf)){ conTinue; } else{ echo $buf."\n"; } } fclose($fp); } ?>
读取标准输入
<?PHP $fp = fopen("/dev/stdin","r"); while($input = fgets($fp,10000)){ $input = trim($input); echo $input."\n"; } fclose($fp); ?>
3. Python
读取标准输入
#coding=utf-8 # 如果要在python2的py文件里面写中文,则必须要添加一行声明文件编码的注释,否则python2会默认使用ASCII编码。 # 编码申明,写在第一行就好 import sys input = sys.stdin for i in input: #i表示当前的输入行 i = i.Strip() print i input.close()
4. SHell
读取文件
读取标准输入
以上这篇C++/PHP/Python/SHell 程序按行读取文件或者控制台的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。
以上是大佬教程为你收集整理的C++/Php/Python/Shell 程序按行读取文件或者控制台的实现全部内容,希望文章能够帮你解决C++/Php/Python/Shell 程序按行读取文件或者控制台的实现所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。