溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++/Php/Python/Shell程序如何按行讀取文件或者實現(xiàn)控制臺

發(fā)布時間:2021-07-26 10:30:04 來源:億速云 閱讀:183 作者:小新 欄目:編程語言

小編給大家分享一下C++/Php/Python/Shell程序如何按行讀取文件或者實現(xiàn)控制臺,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

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表示當前的輸入行

  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)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI