一些語言的按行讀取文件的代碼實(shí)現(xiàn)小結(jié)
更新時(shí)間:2015年08月07日 11:01:21 作者:zinss26914
這篇文章主要介紹了一些語言的按行讀取文件的代碼實(shí)現(xiàn)小結(jié),這里羅列了Java和C語言和C++以及PHP的實(shí)現(xiàn)需要的朋友可以參考下
Java實(shí)現(xiàn)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class JavaFile {
public static void main(String[] args) {
try {
// read file content from file
StringBuffer sb= new StringBuffer("");
FileReader reader = new FileReader("c://test.txt");
BufferedReader br = new BufferedReader(reader);
String str = null;
while((str = br.readLine()) != null) {
sb.append(str+"/n");
System.out.println(str);
}
br.close();
reader.close();
// write string to file
FileWriter writer = new FileWriter("c://test2.txt");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(sb.toString());
bw.close();
writer.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
C++實(shí)現(xiàn)
#include<string>
#include<iostream>
#include<stdlib.h>
#include<fstream>
int main()
{
std::string file_name="123";
std::ifstream fin(file_name.c_str());
std::string textline[3];
for(int i=0;i<3;++i)
getline(fin,textline[i],'\n');//遇到換行結(jié)束這一行的讀取
for(int i=0;i<3;++i)
std::cout<<textline[i]<<'\n';
return 0;
}
php實(shí)現(xiàn)
<?php
/**
* 按行讀取文件
* @param string $filename
*/
function readFileByLine ($filename)
{
$fh = fopen($filename, 'r');
while (! feof($fh)) {
$line = fgets($fh);
echo $line;
}
fclose($fh);
}
// test
$filename = "/home/wzy/test/sort.txt";
readFileByLine($filename);
c語言實(shí)現(xiàn)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 1024
int main(void)
{
char filename[LEN], buf[LEN];
FILE *fp;
int len;
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) exit(-1);
while (fgets(buf, LEN, fp) != NULL) {
len = strlen(buf);
buf[len - 1] = '\0'; // 去掉換行符
printf("%s\n", buf);
}
return 0;
}
相關(guān)文章
c語言中字符串分割函數(shù)及實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄猚語言中字符串分割函數(shù)及實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-05-05
C語言采用文本方式和二進(jìn)制方式打開文件的區(qū)別分析
這篇文章主要介紹了C語言采用文本方式和二進(jìn)制方式打開文件的區(qū)別分析,有助于讀者更好的理解文本文件與二進(jìn)制文件的原理,需要的朋友可以參考下2014-07-07
C++ OpenCV實(shí)現(xiàn)圖像雙三次插值算法詳解
圖像雙三次插值的原理,就是目標(biāo)圖像的每一個(gè)像素都是由原圖上相對(duì)應(yīng)點(diǎn)周圍的4x4=16個(gè)像素經(jīng)過加權(quán)之后再相加得到的。本文主要介紹了通過C++ OpenCV實(shí)現(xiàn)圖像雙三次插值算法,需要的可以參考一下2021-12-12

