The C++ and Php and Python and Shell program reads a file or console implementation by line

  • 2020-05-17 06:07:40
  • OfStack

Writing programs often requires reading information by line from a file or standard input. Here's a summary. Easy to use

1. C++

Read the file


#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];
  // Read the contents of the file by line 
  while(fgets(buf, sizeof(buf), p_in) != NULL) {
    // Write to file 
    fwrite(buf, sizeof(char), strlen(buf), p_out);
  }

  fclose(p_in);
  fclose(p_out);
  return 0;
}

Read standard input


#include<stdio.h>

int main(){
  char buf[2048];

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

  return 0;
}

/// scanf  Characters such as Spaces end when encountered 
/// gets  The end of a newline is encountered 

2. Php

Read the file


<?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)  Does not specify the length to default to 1024 byte 
    $buf = fgets($fp);

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

Read standard input


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

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

fclose($fp);
?>

3. Python

Read standard input


#coding=utf-8

#  If you want to in python2 the py If you write Chinese in the file, you must add it 1 Line declaration file encoding comments, otherwise python2 Will be used by default ASCII Encoding. 
#  Code declaration, write in the first 1 It is good to do  
import sys

input = sys.stdin

for i in input:
  #i Represents the current input line 

  i = i.strip()
  print i

input.close()

4. Shell

Read the file


#!/bin/bash

# Read the file ,  Use the file name directly ;  Read console ,  Use the /dev/stdin

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

Read standard input


#!/bin/bash

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

Related articles: