• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

c++ 搞代码 4年前 (2022-01-06) 20次浏览 已收录 0个评论

下面小编就为大家带来一篇C++/Php/Python/Shell 程序按行读取文件或者控制台的实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

1. C++

 读取文件

 #include #include 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){ <div style="color:transparent">来源gaodai.ma#com搞#代!码网</div>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 int main(){ char buf[2048]; gets(buf); printf("%s\n", buf); return 0; } /// scanf 遇到空格等字符会结束 /// gets 遇到换行符结束

2. Php

读取文件

 

读取标准输入 

 

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

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

以上就是C++/Php/Python/Shell 程序按行读取文件或者控制台的实现的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++/Php/Python/Shell 程序按行读取文件或者控制台的实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址