How to process a file line by line?

How to process a file line by line? The file is a plain text line like input.txt. As an example, the process can be to just print it out.

asked Mar 29 by SA (200 points)

5 Answers

In Bash:

while read line ; do
    echo $line
done < ./input.txt

Reference: https://www.systutorials.com/qa/2166/how-to-process-a-file-line-by-line-in-go

answered Mar 29 by SA (200 points)

In Go, you can make use of the bufio package's Scan().

// open the file filepath
f := os.Open(filepath)
// create a scanner
fs := bufio.NewScanner(f)

// scan file https://golang.org/pkg/bufio/#Scanner.Scan
for fs.Scan() {
        txt := fs.Text()
        // do anything with txt
}

Reference: https://www.systutorials.com/qa/2166/how-to-process-a-file-line-by-line-in-go

answered Mar 29 by SA (200 points)

In Python:

with open("./input.txt", "r") as thefile:
  for line in thefile:
    print line

Reference: https://www.systutorials.com/qa/2387/how-to-process-a-file-line-by-line-in-python

answered Mar 31 by zma (2,200 points)
edited Apr 10 by zma

In PHP, you can use this code snippet:

if ( ($fhandle = fopen("./input.txt", "r") !== FALSE ) {
  while (($line = fgets($fhandle)) !== false) {
    echo $line
  }

  fclose($handle);
} else {
  // error handling
} 
answered Apr 10 by zma (2,200 points)

In C++, you may open a input stream on the file and use the std::getline() function from the <string> to read content line by line into a std::string and process them.

std::ifstream file("input.txt");
std::string str; 
while (std::getline(file, str)) {
  // process string ...
}

A full example is as follows:

$ g++ file-read-line.cpp -o s && ./s
$ cp file-read-line.cpp input.txt
$ ./s
#include <iostream>
#include <fstream>
#include <string>

int main ()
{
  std::ifstream file("input.txt");
  std::string str;
  while (std::getline(file, str)) {
    std::cout << str << "\n";
  }
}
answered Apr 18 by zma (2,200 points)

Please log in or register to answer this question.

Related questions

8 answers
asked Apr 6 by anonymous
4 answers
0 answers
0 answers
asked Apr 10 by anonymous
Welcome to Do This In Various Langs (dtivl), where you can ask questions and receive solutions in various programming languages.
Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...