c_cpp 逐行读取一个巨大的文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 逐行读取一个巨大的文件相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env python
import sys
def work(path):
char_counter = 0
line_counter = 0
with open(path, 'rb') as f:
for line in f:
char_counter += len(line)
line_counter += 1
print "Read finished, total lines: %d, total chars: %d" % (line_counter, char_counter)
if __name__ == "__main__":
p = sys.argv[1]
work(p)
'use strict';
const readline = require('readline');
const fs = require('fs');
function work(path) {
let rl = readline.createInterface({
input: fs.createReadStream(path, 'binary')
});
let char_counter = 0;
let line_counter = 0;
rl.on('line', line => {
char_counter += line.length+1;
line_counter++;
}).on('close', ()=> {
console.log('Read finished, total lines: %d, total chars: %d', line_counter, char_counter);
});
}
if (typeof module !== 'undefined' && module.parent) {
} else {
// test code go here
let p = process.argv[2];
work(p);
}
package main
import (
"fmt"
"bufio"
"os"
"log"
)
func readline(path string) {
f, err := os.Open(path)
if err != nil {
log.Panic("opening file failed")
}
defer f.Close()
sc := bufio.NewScanner(f)
var char_counter, line_counter int
for sc.Scan() {
line := sc.Text()
char_counter += len(line)+1
line_counter++
}
if err = sc.Err(); err != nil {
log.Panic("scanner error")
}
fmt.Printf("Read finished. Total lines: %d, total chars: %d\n", line_counter, char_counter)
}
func main() {
p := os.Args[1]
readline(p)
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
int char_counter = 0;
int line_counter = 0;
ifstream f;
string line;
f.open(argv[1]);
while (!f.eof()) {
getline(f, line);
char_counter += (line.length()+1);
line_counter++;
}
cout << "Read finished, total lines: " << line_counter << ", total chars: " << char_counter << endl;
}
以上是关于c_cpp 逐行读取一个巨大的文件的主要内容,如果未能解决你的问题,请参考以下文章
在 Node.js 中解析巨大的日志文件 - 逐行读取
如何通过 javascript 或 jquery 读取巨大的文本文件?
Bash怎么逐行读取一个文件
c_cpp 逐行阅读
逐行读取文件
逐行读取 CSV 文件 python