C++/Php/Python/Shell 程序按行讀取文件或者控制臺的實現(xiàn)
更新時間:2017年03月31日 14:20:11 投稿:jingxian
下面小編就為大家?guī)硪黄狢++/Php/Python/Shell 程序按行讀取文件或者控制臺的實現(xiàn)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
寫程序經(jīng)常需要用到從文件或者標準輸入中按行讀取信息,這里匯總一下。方便使用
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];
//按行讀取文件內(nèi)容
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 遇到空格等字符會結(jié)束
/// gets 遇到換行符結(jié)束
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表示當(dāng)前的輸入行 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 程序按行讀取文件或者控制臺的實現(xiàn)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python實現(xiàn)讀取文件最后n行的方法
- Python按行讀取文件的實現(xiàn)方法【小文件和大文件讀取】
- Python按行讀取文件的簡單實現(xiàn)方法
- Python3實現(xiàn)從文件中讀取指定行的方法
- python逐行讀取文件內(nèi)容的三種方法
- python讀文件逐行處理的示例代碼分享
- python追加元素到列表的方法
- Python文件操作,open讀寫文件,追加文本內(nèi)容實例
- Python中使用第三方庫xlutils來追加寫入Excel文件示例
- Python創(chuàng)建文件和追加文件內(nèi)容實例
- Python實現(xiàn)的將文件每一列寫入列表功能示例【測試可用】
相關(guān)文章
C語言學(xué)習(xí)進階篇之萬字詳解指針與qsort函數(shù)
之前的指針詳解中,提到過qsort函數(shù),這個函數(shù)是用來排序的,下面這篇文章主要給大家介紹了關(guān)于C語言指針與qsort函數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08

