Writing programs often need to read information by line from a file or standard input, summarized here. Easy to use
1. C + +
Read file
1#include <stdio.h>2#include <string.h>3 4 intMain () {5 Const Char* In_file ="Input_file_name";6 Const Char* Out_file ="Output_file_name";7 8FILE *p_in = fopen (In_file,"R");9 if(!p_in) {Tenprintf"Open file%s failed!!!", in_file); One return-1; A } - -FILE *p_out = fopen (Out_file,"W"); the if(!p_in) { -printf"Open file%s failed!!!", out_file); - if(!p_in) { - fclose (p_in); + } - return-1; + } A at Charbuf[2048]; - //read file contents by line - while(Fgets (BUF,sizeof(BUF), p_in)! =NULL) { - //Write to File -Fwrite (BUF,sizeof(Char), strlen (BUF), p_out); - } in - fclose (p_in); to fclose (p_out); + return 0; -}
View Code
Reading standard input
1#include <stdio.h>2 3 intMain () {4 Charbuf[2048];5 6 gets (BUF);7printf"%s\n", buf);8 9 return 0;Ten } One A ///scanf encounters a space and other characters will end - ///gets encounters line break end
View Code
2. Php
Read file
1<?PHP2 $filename= "Input_file_name";3 4 $fp=fopen($filename, "R");5 if(!$fp){6 EchoThe Open File$filenamefailed\n ";7 Exit(1);8 }9 Else{Ten while(!feof($fp)){ One //fgets (file,length) does not specify a length of 1024 bytes by default A $buf=fgets($fp); - - $buf=Trim($buf); the if(Empty($buf)){ - Continue; - } - Else{ + Echo $buf." \ n "; - } + } A fclose($fp); at } -?>
View Code
Reading standard input
1<?PHP2 $fp=fopen("/dev/stdin", "R");3 4 while($input=fgets($fp, 10000)){5 $input=Trim($input);6 Echo $input." \ n ";7 }8 9 fclose($fp);Ten?>
View Code
3. Python
Reading standard input
1 #Coding=utf-82 3 #If you want to write Chinese in the Python2 py file, you must add a line to declare the file encoded comments, otherwise python2 will use ASCII encoding by default. 4 #coding statement, written in the first line is good5 ImportSYS6 7input =Sys.stdin8 9 forIinchInput:Ten #I represents the current input line One Ai =I.strip () - PrintI - theInput.close ()
View Code
4. Shell
Read file
1 #!/bin/bash23 #读取文件, use the file name directly; To read the console, use/dev/stdin45 while the readline6do7 echo ${line}8 done < filename
View Code
Reading standard input
1 #!/bin/bash23 while readline4do5 echo ${line}6 Done </dev/stdin
View Code
C++/php/python/shell program reads files by line or console