欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

C++/Php/Python/Shell 程序按行讀取文件或者控制臺(tái)的實(shí)現(xiàn)

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊: 次

寫程序經(jīng)常需要用到從文件或者標(biāo)準(zhǔ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;
}

讀取標(biāo)準(zhǔn)輸入

#include<stdio.h>

int main(){
  char buf[2048];

  gets(buf);
  printf("%s\n", buf);

  return 0;
}

/// scanf 遇到空格等字符會(huì)結(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) 不指定長(zhǎng)度默認(rèn)為1024字節(jié)
    $buf = fgets($fp);

    $buf = trim($buf);
    if(empty($buf)){
      continue;
    }
    else{
      echo $buf."\n";
    }
  }
  fclose($fp);
}
?>

讀取標(biāo)準(zhǔn)輸入 

<?php
$fp = fopen("/dev/stdin", "r");

while($input = fgets($fp, 10000)){
    $input = trim($input);
    echo $input."\n";
}

fclose($fp);
?>

3. Python

讀取標(biāo)準(zhǔn)輸入

#coding=utf-8

# 如果要在python2的py文件里面寫中文,則必須要添加一行聲明文件編碼的注釋,否則python2會(huì)默認(rèn)使用ASCII編碼。
# 編碼申明,寫在第一行就好 
import sys

input = sys.stdin

for i in input:
  #i表示當(dāng)前的輸入行

  i = i.strip()
  print i

input.close()

4. Shell

讀取文件

#!/bin/bash

#讀取文件, 則直接使用文件名; 讀取控制臺(tái), 則使用/dev/stdin

while read line
do
  echo ${line}
done < filename

讀取標(biāo)準(zhǔn)輸入

#!/bin/bash

while read line
do
  echo ${line}
done < /dev/stdin

以上這篇C++/Php/Python/Shell 程序按行讀取文件或者控制臺(tái)的實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持我們。

上一篇:C語言基礎(chǔ)之格式化輸出控制長(zhǎng)度

欄    目:C語言

下一篇:C語言中的const和free用法詳解

本文標(biāo)題:C++/Php/Python/Shell 程序按行讀取文件或者控制臺(tái)的實(shí)現(xiàn)

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/1667.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有