写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下。方便使用
1. C++
读取文件
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#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;
}
|
读取标准输入
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include<stdio.h>
int main(){
char buf[2048];
gets(buf);
printf("%s\\n", buf);
return 0;
}
/// scanf 遇到空格等字符会结束
/// gets 遇到换行符结束
|
2. Php
读取文件
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?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);
}
?>
|
读取标准输入
?
|
1
2
3
4
5
6
7
8
9
10
|
<?php
$fp = fopen("/dev/stdin", "r");
while($input = fgets($fp, 10000)){
$input = trim($input);
echo $input."\\n";
}
fclose($fp);
?>
|
3. Python
读取标准输入
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#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
读取文件
?
|
1
2
3
4
5
6
7
8
|
#!/bin/bash
#读取文件, 则直接使用文件名; 读取控制台, 则使用/dev/stdin
while read line
do
echo ${line}
done < filename
|
读取标准输入
?
|
1
2
3
4
5
6
|
#!/bin/bash
while read line
do
echo ${line}
done < /dev/stdin
|
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 27
-
2025-05-25 52
-
2025-05-25 73
-
Windows 8系统怎么升级成Windows 11系统,Windows 8升级Windows 11系统操作步骤
2025-05-27 101 -
2025-06-04 59
热门评论

