C++/Php/Python/Shell 程序按行读取文件或者控制台的实现

2025-05-27 0 60

写程序经常需要用到从文件或者标准输入中按行读取信息,这里汇总一下。方便使用

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

以上这篇C++/Php/Python/Shell 程序按行读取文件或者控制台的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++/Php/Python/Shell 程序按行读取文件或者控制台的实现 https://www.kuaiidc.com/73482.html

相关文章

发表评论
暂无评论