C++/Php/Python/Shell 程序按行读取文件或者控制台的实现
作者:jingxian 时间:2021-12-20 06:36:18
写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下。方便使用
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
读取文件
#!/bin/bash
#读取文件, 则直接使用文件名; 读取控制台, 则使用/dev/stdin
while read line
do
echo ${line}
done < filename
读取标准输入
#!/bin/bash
while read line
do
echo ${line}
done < /dev/stdin
标签:python,控制台,C++,Php,Python,Shell
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Mootools 1.2教程(11)——Fx.Morph、Fx选项和Fx事件
2008-12-04 16:03:00
SQL 判断给定日期值(或时间段)所在星期的星期一和星期天的日期
2011-10-24 20:14:52
如何解决“cint和clng的溢出出错”问题?
2009-12-03 20:21:00
AJAX和DOM的运行经验
2008-05-02 21:05:00
php flv视频时间获取函数
2023-09-04 13:41:48
CSS雪碧:要还是不要?
2009-11-16 13:01:00
SQL大讲堂:如何了解SQL的执行频率
2009-09-05 09:40:00
带你轻松接触MySQL数据库的出错代码列表
2008-12-31 15:06:00
使用SQL Server 2008中对象相关性
2008-12-12 06:36:00
Data URI 和 MHTML
2009-08-16 16:19:00
如何增大MYSQL数据库连接数
2010-10-25 20:28:00
详解PHP设计模式之桥接模式
2023-05-30 10:29:02
基于Python绘制520表白代码
2021-06-10 08:14:44
![](https://img.aspxhome.com/file/2023/6/64346_0s.png)
让长字符自动换行 比如URL和Email地址等
2008-07-01 14:41:00
asp如何编写一个DNS LOOKUP程序?
2009-11-07 18:47:00
彻底终结浏览器Cache页面的解决方案
2008-04-21 15:10:00
用ajax实现的自动投票的代码
2023-08-24 16:35:07
python实现批量提取指定文件夹下同类型文件
2023-11-17 17:13:31
![](https://img.aspxhome.com/file/2023/4/63934_0s.jpg)
windows下使用GoLand生成proto文件的方法步骤
2023-08-25 16:04:21
![](https://img.aspxhome.com/file/2023/2/99632_0s.jpg)
php下pdo的mysql事务处理用法实例
2023-11-14 17:44:13