C++/Php/Python/Shell 程序按行讀取文件或者控制臺的實現
更新時間:2017年03月31日 14:20:11 投稿:jingxian
下面小編就為大家?guī)硪黄狢++/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字節(jié)
$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 程序按行讀取文件或者控制臺的實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

