您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
小编给大家分享一下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
读取文件
#!/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程序如何按行读取文件或者实现控制台”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。