C********a 发帖数: 10 | 1 想不明白BufferedReader.readLine()是怎么回事 如果是读文件的话,每叫一次
readLine()就读取文件的下一行,并且返回一个String;如果读到EOF就返回null。
比如
BufferedReader br = new BufferedReader("c:/test.txt");
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
那如果读的是一个inputstream呢 像下面
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out... 阅读全帖 |
|
k***t 发帖数: 276 | 2 自己顶一下,大拿们都不屑于写这个readLine()吗?
这道readLine()的题到底想考什么?
StackOverflow上的一个comment说要考security和memleak。
Implement a function
char* readLine();
which returns single lines from a buffer. To read the buffer, you can makes
use of a function
int read(char* buf, int len)
which fills buf with upto len chars and returns the actual number of chars
filled in. Function readLine can be called as many times as desired. If
there is no valid data or newline terminated string available, it must block
. In order to bloc... 阅读全帖 |
|
h**o 发帖数: 548 | 3 出境率很高,但众说纷纭,没看见合适的答案。
贴一个我的吧,包括read(dst, n) 和readline(). 欢迎讨论.
#define FOURK 4096
class readbuf{
readbuf(){remain = 0; ptr = 0;}
char buf[FOURK];
int ptr; //start ptr of buf to catch
int remain; //byte remains in buf
int readN(char*dst, int n);
int readLine(string& s);
};
int readbuf::readN(*dst, int n){
if (!dst) return 0;
int bytes = 0;
while(n>0){
if (remain==0) {nRead = read4K(buf); remain = nRread; ptr = 0;}
min = min(n, remain);
bytes+=memc... 阅读全帖 |
|
c*****t 发帖数: 1879 | 4 These has nothing to do with readline. Only programs that use readline
APIs will utilize readline.dll. |
|
k***t 发帖数: 276 | 5 谁写了?或有没有好一些的online的参考答案?
用于对照检查自己写的是否全面。谢谢。
发信人: xicheng17 (super), 信区: JobHunting
标 题: fb面试题【转】
发信站: BBS 未名空间站 (Wed Nov 9 20:42:44 2011, 美东)
不知道发过没,在其他地方看到的。
Implement a function
char* readLine();
which returns single lines from a buffer. To read the buffer, you can makes
use of a function
int read(char* buf, int len)
which fills buf with upto len chars and returns the actual number of chars
filled in. Function readLine can be called as many times as desired. If
there is no valid data or newl... 阅读全帖 |
|
h**o 发帖数: 548 | 6 贴个我的吧:
#define FOURK 4096
class readbuf{
readbuf(){nsize = 0; ptr = 0;}
char buf[FOURK];
int ptr;
int nsize;
int readN(char*dst, int n);
int readLine(string& s);
};
int readbuf::readN(*dst, int n){
if (!dst) return 0;
int bytes = 0;
while(n>0){
if (nsize==0) {nRead = read4K(buf); nsize = nRread; ptr = 0;}
min = min(n, nsize);
bytes+=memcpy(dst+bytes, buf, min);
ptr+=min; n-=min; nsize-=min;
if (nRead0 or ==0... 阅读全帖 |
|
C********a 发帖数: 10 | 7 谢谢! 但是如果不等待输入的话 这个循环是怎么工作的呢
while((message=reader.readLine())!=null){
System.out.println("read"+message);}
完整代码
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){
try{
sock=clientSocket;
InputStreamReader isReader=new InputStreamReader(sock.
getInputStream());
reader=new BufferedReader(isReader);
}c... 阅读全帖 |
|
m**w 发帖数: 76 | 8 安装了GnuWin32之后, 可以看到readline.dll, 但是在cmd命令行下不能用readline的
快捷键.
哪位大虾知道怎么配置? 先谢了. |
|
n****e 发帖数: 678 | 9 Implement readline using read4096
这道题之前版上有讨论过,不知道有没有标准的解答codes
网上搜了搜,感觉网上贴的codes都不太对。
多谢! |
|
h**o 发帖数: 548 | 10 usually there are two FAQ about this topic, sometimes readN(char* dst, int
size) is asked during interview, given read4096(char* buf); sometimes
readLine(char* dst) is asked, given read4096(char* buf). I am writing both. |
|
n****e 发帖数: 678 | 11 Implement readline using read4096
这道题之前版上有讨论过,不知道有没有标准的解答codes
网上搜了搜,感觉网上贴的codes都不太对。
多谢! |
|
h**o 发帖数: 548 | 12 usually there are two FAQ about this topic, sometimes readN(char* dst, int
size) is asked during interview, given read4096(char* buf); sometimes
readLine(char* dst) is asked, given read4096(char* buf). I am writing both. |
|
y***n 发帖数: 1594 | 13 readN 和 readLine 都是一个思路吗? |
|
h**o 发帖数: 548 | 14 int readbuf::readLine(string& s){
int bytes = 0; bool endline = false;
while(1){
if (nsize==0) {nRead = read4K(buf); nsize = nRread; ptr = 0;}
for(; ptr< FOURK && nsize>0;ptr++, nsize--) {
s.append (buf[ptr]); bytes++;
if (buf[ptr] == ' 0 ' || buf[ptr] ==' n') endline=true;
}
if (endline || nRead
}
} |
|
w*s 发帖数: 7227 | 15 so i open this url with
fh = urllib2.urlopen()
for eachline in fh.readlines()
print eachline
.........
now i want to go back to the beginning, and parse the page again.
is there a seek(0) or ? |
|
a9 发帖数: 21638 | 16 fh = urllib2.urlopen()
fl = fh.readlines()
for eachline in fl:
print eachline
for eachline in fl:
print eachline
这样? |
|
b*******e 发帖数: 288 | 17 有的呀
不过用的时候小心,这个是把所有line全部读出,太大的文件内存就满了,readline()
是一次读一行 |
|
z***m 发帖数: 1602 | 18 Given 2 functions String recv() and String ReadLine()
recv() generates some string (Example:"123n45n6789").
ReadLine() should read the string being returned by recv() and print all
characters until the first n.
After that it should read the recv() string again and print the next
characters until the 2nd n.
Example: recv(): "123n45n6789"
ReadLine(): "123" //first call of ReadLine
ReadLine(): "45" // second call of ReadLine
However, the next sequence now doesn't have ... 阅读全帖 |
|
n******1 发帖数: 3756 | 19 我在网上看到这两段代码,一个写,一个读,但是好像是有问题的.我看写是没问题的
,我把queue打出来,输入的都有,但是reader的读行为非常奇怪,如果文件有内容,
可以读出来,但是重新写入的有时候能读一部分,比如writer写入abcde,可能read到ab
出来,但大部分时间都是null,尝试自己加过在writer加入sleep,wait什么都没用
Writer.java
import java.io.BufferedWriter;
import java.io.Console;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.logging... 阅读全帖 |
|
b*******S 发帖数: 17 | 20 我沒有去看python的code 不過就猜猜看 只是推理
http://docs.python.org/library/stdtypes.html?
highlight=readlines#file.readlines
裡面說Files support the iterator protocol. Each iteration returns the same
result as readline(), and iteration ends when the readline() method returns
an empty string.
所以你stackoverflow裡面的例子
for line in file.readlines():
#preprocess line
yield line
這樣搞不好就是直接弄個iterator來,每次就叫file.readline()去抓一行
如果是這樣的case,那當然就會省空間了 |
|
s********u 发帖数: 1109 | 21 挖个坟,这个readline的题目,搜了一下,好像应该是这个意思吧:
用一个buffer来存字符流,如果中间有换行,那么将这一行返回成一个字符串输出,但
是这个buffer里面的东西继续保留,下次readline()再输出;
如果一行非常长,那么可能需要用到几次read(),来拼出这个完整的line。
/*Implement a function char* readLine(); which returns single lines from a
buffer.
To read the buffer, you can makes use of a function int read(char* buf, int
len) which fills buf with upto len chars and returns the actual number of
chars filled in. Function readLine can be called as many times as desired.
If there is no valid data or newline ter... 阅读全帖 |
|
l****n 发帖数: 55 | 22 Thanks.
I tried
s = infile.readLine()
s = infile.readLine().replaceAll("\\n+", "")
s = infile.readLine().replaceAll("[\n\r\t]+", "")
s = infile.readLine().replaceAll("\r\n|\r|\n", "")
s = infile.readLine().replaceAll("\\n", "")
It's very strange that none of them work. |
|
z**********g 发帖数: 209 | 23 给你一个 char* read4096() 的API,一次返回小于或者等于4096个字符。
如果返回是小于4096个字符,意味着已经读到文件末尾 '\0'。
用read4096()这个API,写一个 char* readline() 的function。
要求:
#1 readline()returns when reading '\n' or '\0';
#2 readline() may be called multiple times on a file, the return value
should be correct.
#3 readline() may return char array longer than 4096 chars.
挣扎了半天,超时了。move on 了。 |
|
p*****2 发帖数: 21240 | 24 刚做了一个小题。不知道第二种写法面试会不会悲剧?
object test2 extends App {
val n=readLine.toInt
val a=readLine.split(" ").map(_.toInt)
var max=0
for(i<-0 until n)
{
var value=a(i)
max=math.max(max,a(i))
for(j<-i+1 until n)
{
value^=a(j)
max=math.max(max,value)
}
}
println(max)
}
object test2 extends App {
val n=readLine.toInt
val a=readLine.split(" ").map(_.toInt)
println((for(i<-0 until n) yield for(j<-i+1 to n... 阅读全帖 |
|
w*j 发帖数: 336 | 25 使用的是http://jeff.doozan.com/debian/的script, 安装完debian后,在第STEP 2,运行dpkg-reconfigure locales, 但进行不下去了,说/usr/sbin/dpkg-reconfigure: locales is not installed。求解,谢谢
root@debian:~# dpkg-reconfigure locales
debconf: unable to initialize frontend: Dialog
debconf: (No usable dialog-like program is installed, so the dialog based
frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line
75.)
debconf: falling back to frontend: Readline
debconf: unable to initialize frontend: Readline
debco... 阅读全帖 |
|
s****a 发帖数: 50 | 26 这个只能调用read每次读一个字符吧。还有什么其他trick?
4。给定int read(char *buffer, int size) api,写出int readline(char * buffer,
int size)code。举例说,输入一个字符串“abcd\nefgh”,read(buffer,3)返回3,
buffer=abc,同时指针指向字符"d"。read(buffer,7)返回7,buffer=abcd\nef,同时
指针指向字符"g"。返回值是实际读取的字符数。要求readline(buffer,3)返回3,
buffer=abc,同时指针指向字符"d"。readline(buffer,7)返回4,buffer=abcd,同时
指针指向字符"e"。
有个trick point,一开始我没注意,后来写对了。他们看上去很满意。 |
|
j***u 发帖数: 16 | 27 如果C/C++的话,会有些问题。
按题意思, readline返回的字符是可以大于4096的
那就是说当在readline内部调用 read4096的时候,
readline 无法预先确认这个文件究竟有多大,所以如果是
java就不用考虑这个问题,只要stringbuffer.append就可以。
但在C/C++, 恐怕要反复重新分配动态数组,同时还要释放。
比如你先申请char *p = new str[4096], 当超过的时候,
你必须要重新分配新的数组,然后拷贝,同时释放旧数组。
应该在一个循环里面解决。
他们考这个够狠的. |
|
e****e 发帖数: 418 | 28 public class LineReader {
private int pos = 0;
private List chars = null;
public Character[] readLine() {
if ( chars == null || chars.size() == 0 )
chars = Arrays.asList( read4096() );
List line = new ArrayList();
int i = pos;
while ( i < chars.size() && chars.get(i) != '\n' && chars.get(i) !=
'\0' )
line.add( chars.get(i++) );
if ( chars.get(i) == '\n' ) {
... 阅读全帖 |
|
p*****2 发帖数: 21240 | 29 我写了一个。看看有没有问题?
import collection.mutable.{Map, Queue}
object test2 extends App {
val Array(n,k)=readLine.split(" ").map(_.toInt)
val start=readLine.split(" ").map(_.toInt-1).mkString(" ") //pegs and
discs start from 0
val end=readLine.split(" ").map(_.toInt-1).mkString(" ")
val queue=new Queue[String]()
val map=Map[String,String]()
var distance=0
var count=1
queue+=end
map(end)=null
while(count>0){
distance+=1
while(count>0){
... 阅读全帖 |
|
p*****2 发帖数: 21240 | 30 我写了一个。看看有没有问题?
import collection.mutable.{Map, Queue}
object test2 extends App {
val Array(n,k)=readLine.split(" ").map(_.toInt)
val start=readLine.split(" ").map(_.toInt-1).mkString(" ") //pegs and
discs start from 0
val end=readLine.split(" ").map(_.toInt-1).mkString(" ")
val queue=new Queue[String]()
val map=Map[String,String]()
var distance=0
var count=1
queue+=end
map(end)=null
while(count>0){
distance+=1
while(count>0){
... 阅读全帖 |
|
S***8 发帖数: 13 | 31 来自主题: JobHunting版 - FB 面筋 第一题,我把我当时面试的代码贴上来,可能还有问题,但面试官说可以了
class File {
static String buffer = "";
String readLine() {
if(!buffer.equals("")) { // we have characters left last time
StringBuilder sb = new StringBuilder();
int i = 0;
while(buffer.charAt(i) != '\n' && i < buffer.length()) { //
read one line
sb.append(buffer.charAt(i));
i++;
}
buffer = buffer.substring(i + 1);
if(i == buffer.length()) { // we have so... 阅读全帖 |
|
x*****u 发帖数: 3419 | 32 try this:
http://mult.ifario.us/p/ghc-6-6-and-mac-os-x-readline-quick-fix
GHC 6.6 and Mac OS X Readline Quick Fix
Paul Brown @ 2006-10-17T06:59:00Z
If you build vanilla GHC 6.6 from the source tarball on Mac OS X (non-Intel)
, it will build straight through with no issues, but the ghci commandline
interface will drive you crazy because it lacks support for editing. This is
due to a damaged readline that ships with Mac OS X, but here's a quick fix.
The first step is installing an up-to-date versi |
|
w****i 发帖数: 964 | 33 Could someone tell me how to free memory of huge strings in python?
I have two huge strings R0 and R1 in python, why "R0 = R1" doesn't free the
memory of previous R0?
for example, this frees the memory of R0:
>>> R0 = open(file1).readlines()
>>> del R0
But the following doesn't free memory
>>> R0 = open(file1).readlines()
>>> R1 = open(file2).readlines()
>>> R0 = R1 # this doesn't free memory of file1.
>>> del R0
>>> del R1 # this doesn't free the memory either
what is the best way to free |
|
x*******7 发帖数: 223 | 34 不知道发过没,在其他地方看到的。
Implement a function
char* readLine();
which returns single lines from a buffer. To read the buffer, you can makes
use of a function
int read(char* buf, int len)
which fills buf with upto len chars and returns the actual number of chars
filled in. Function readLine can be called as many times as desired. If
there is no valid data or newline terminated string available, it must block
. In order to block, it can use read function which in turn will block when
it doesn't have anyth... 阅读全帖 |
|
h*****g 发帖数: 312 | 35 Implement a function
char* readLine();
which returns single lines from a buffer. To read the buffer, you can makes
use of a function
int read(char* buf, int len)
which fills buf with upto len chars and returns the actual number of chars
filled in. Function readLine can be called as many times as desired. If
there is no valid data or newline terminated string available, it must block
. In order to block, it can use read function which in turn will block when
it doesn't have anything to fill the b... 阅读全帖 |
|
n*******s 发帖数: 482 | 36 readline()内部要有一个buffer来缓存以减少IO operation.
assume 该缓存是
static char buff[MAX]
static int size ; // current bond of the data in buffer
static int index ; // index of current reader pointer in the buffer
static char resultBuff[MAX]
另外 几个case需要考虑到
(1) there is a '\n' between index and size : just copy them out and return.
and update index.
(2) no '\n' between index and size, now things get complicated
no matter what, need to save the current data between index and max to
resultBuffer, set index to... 阅读全帖 |
|
l***h 发帖数: 392 | 37 这个题目主要是靠第二点和第三点。
#include
#include
#define BLOCK 40
size_t readblock(FILE *fp, char* buffer){
return fread(buffer,1,BLOCK,fp);
};
size_t readline(FILE *fp, char *buf){
long pos = ftell(fp); // record the currently position
int offset = 0;
int num;
while( num = readblock(fp, buf+offset)){
int i;
for( i=0; i
char c = buf[offset];
if(... 阅读全帖 |
|
s******c 发帖数: 99 | 38 import java.io.*;
public class Solution {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.
in));
String line = br.readLine();
int N = Integer.parseInt(line);
String []strs=new String[N];
for (int i = 0; i < N; i++) {
strs[i]=br.readLine();
}
for(int i=0;i
{
char start=strs[i].charAt(0);
int sumtotal=0... 阅读全帖 |
|
i******s 发帖数: 301 | 39 这不就是抄interviewstreet上的么.
下面是我的python code,idea一样,处理重复有一点技巧,你可以自己想想。Time
complexity 应该是O(n^2),主要花在build smaller, greater array上,不过应该能
做到O(nlogn) on average case。我没仔细想过。
import sys
import bisect
arr_size = int(sys.stdin.readline())
arr = map(int, sys.stdin.readline().split())
smaller_than = [0 for i in range(arr_size)]
greater_than = [0 for i in range(arr_size)]
index_map = {}
for i in range(arr_size):
if arr[i] in index_map:
index_map[arr[i]].append(i)
else:
index_map[arr[... 阅读全帖 |
|
p*****2 发帖数: 21240 | 40 刚做了一题,感觉不错。准备好好做做了。哈哈。我这个代码过了第一题
object Solution {
def main(args: Array[String]) {
val n=readLine.toInt
val arr=readLine.split(" ").map(_.toInt)
val last=arr.last
var i=arr.length-2
while(i>=0 && arr(i)>last) {arr(i+1)=arr(i); println(arr.mkString("
"));i-=1}
arr(i+1)=last
println(arr.mkString(" "))
}
} |
|
j**7 发帖数: 143 | 41 http://www.yodlecareers.com/puzzles/triangle.html
我的答案不对 (665321)。
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("triangle.txt");
try
{
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int value=Integer.parseInt(in.readLine().trim());
int index=0;
while ((line = in.readLine()) != nul... 阅读全帖 |
|
s********u 发帖数: 1109 | 42 这是readline那个题我参照网上的代码写的。比这个要复杂一些,因为一个line的字符
是不确定的。
#define MAX_LEN 4096
int read(char* buf, int len);
char *readLine(){
static bool EOF = false;
char *str = NULL;
int i, size = 0;
static int currentPos = MAX_LEN;
static char* buffer = new char[MAX_LEN];
while(!EOF || currentPos != MAX_LEN ){
// buffer is not empty, handle buffer first
if(currentPos != MAX_LEN){
for(i = currentPos; i < MAX_LEN; i++)
... 阅读全帖 |
|
a**d 发帖数: 85 | 43 Implement a function char* readLine(); which returns single lines from a
buffer. To read the buffer, you can makes use of a function int read(char*
buf, int len) which fills buf with upto len chars and returns the actual
number of chars filled in. Function readLine can be called as many times as
desired. If there is no valid data or newline terminated string available,
it must block. In order to block, it can use read function which in turn
will block when it doesn't have anything to fill the bu... 阅读全帖 |
|
R*****i 发帖数: 2126 | 44 CSDN上的编程挑战题。
http://hero.csdn.net/Question/Details?ID=610&ExamID=605
我的算法貌似不对,请问正确算法是神马?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace GridWalk
{
class Program
{
static void Main(string[] args)
{
List nlist = new List();
string line = Console.ReadLine();
while (!string.IsNullOrEmpty(line))
{
nlist.Add(int.Parse(line));
... 阅读全帖 |
|
|
c*******4 发帖数: 51 | 46 详细信息在下面网址:
https://www.thumbtack.com/challenges/simple-database
面试一道题目,题目是设计一个Simple Database,我提交的解法说有问题然后被拒了。
只想各位大神帮我看看code有哪些毛病,feedback说算法不是最优的,function大小写
没有注意。
目前我觉得自己问题在NUMEQUALTO复杂度n不是1,方程都大写了,想请教下还有什么问
题。
下面是我python的代码。再次感谢大家的帮助,我只想知道代码哪里还出了问题。
import sys
class Database(object):
def __init__(self):
self._history = [] #list to store transaction history
self._database = {} #dictionary store key value pair
def BEGIN(self):
self._history.append({})
def S... 阅读全帖 |
|
c*******4 发帖数: 51 | 47 详细信息在下面网址:
https://www.thumbtack.com/challenges/simple-database
面试一道题目,题目是设计一个Simple Database,我提交的解法说有问题然后被拒了。
只想各位大神帮我看看code有哪些毛病,feedback说算法不是最优的,function大小写
没有注意。
目前我觉得自己问题在NUMEQUALTO复杂度n不是1,方程都大写了,想请教下还有什么问
题。
下面是我python的代码。再次感谢大家的帮助,我只想知道代码哪里还出了问题。
import sys
class Database(object):
def __init__(self):
self._history = [] #list to store transaction history
self._database = {} #dictionary store key value pair
def BEGIN(self):
self._history.append({})
def S... 阅读全帖 |
|
f*******r 发帖数: 976 | 48 这种题目都出来了,难度不小啊
详细信息在下面网址:
https://www.thumbtack.com/challenges/simple-database
面试一道题目,题目是设计一个Simple Database,我提交的解法说有问题然后被拒了。
只想各位大神帮我看看code有哪些毛病,feedback说算法不是最优的,function大小写
没有注意。
目前我觉得自己问题在NUMEQUALTO复杂度n不是1,方程都大写了,想请教下还有什么问
题。
下面是我python的代码。再次感谢大家的帮助,我只想知道代码哪里还出了问题。
import sys
class Database(object):
def __init__(self):
self._history = [] #list to store transaction history
self._database = {} #dictionary store key value pair
def BEGIN(self):
self._history.appe... 阅读全帖 |
|
t**d 发帖数: 6474 | 49
什么server?是不是server的模块不全? 我的lighttpd里面用ipkg list_installed显
示有如下模块安装。你的如果没有,就装上这些模块 (不一定要全装)。
expat - 2.0.1-1 - XML Parser library
fcgi - 2.4.0-2 - FastCGI is a language independent, scalable, open extension
to fontconfig - 2.5.0-0 -
freetype - 2.3.6-1 - Free truetype library
gconv-modules - 2.5-1 - Provides gconv modules missing from the firmware.
gdbm - 1.8.3-2 -
libcurl - 7.20.0-1 -
libdb - 4.2.52-3 - Berkeley DB Libraries
libgd - 2.0.35-5 -
libjpeg - 6b-3 - collection of jpeg tools
libpng - ... 阅读全帖 |
|
W******c 发帖数: 23 | 50 31. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time
slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based
on priority and
other factors.
32. Name three Component subclasses that support painting.
Th... 阅读全帖 |
|