PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label readline. Show all posts
Showing posts with label readline. Show all posts

Sunday, October 30, 2022

[FIXED] How to read a textual HTTP response into a String exactly as-is?

 October 30, 2022     bufferedreader, carriage-return, eof, java, readline     No comments   

Issue

The following code uses BufferedReader to read from an HTTP response stream:

final StringBuilder responseBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
    responseBuilder.append(line);
    responseBuilder.append('\n');
    line = bufferedReader.readLine();
}
response = responseBuilder.toString();

But appending '\n' to each line seems a bit flawed. I want to return the HTTP response exactly as-is so what if it doesn't have a return character after the last line? One would get added anyway using the code above - is there a better way?


Solution

I want to return the HTTP response exactly as-is

Don't use readLine() then - it's as simple as that. I'd suggest using a StringWriter instead:

StringWriter writer = new StringWriter();
char[] buffer = new char[8192];
int charsRead;
while ((charsRead = bufferedReader.read(buffer)) > 0) {
    writer.write(buffer, 0, charsRead);
}
response = writer.toString();

Note that even this won't work if you get the encoding wrong. To preserve the exact HTTP response, you'd need to read (and write) it as a binary stream.



Answered By - Jon Skeet
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get the while loop to recognise it is the end of the file

 October 30, 2022     eof, loops, python, readline, while-loop     No comments   

Issue

I have a text file with data that represents Line 1 name, email, phone Line 2 address Line 3 is an integer that says how many friends are listed. Line 4 ~ n Each line consists of a name

I have been able to get each line with

line = infile.readline()

I have a problem when I get to the end of the file.

It wants to loop around again as if it does not recognise the end of the file

infile = open(filename, "r")
lines = infile.readlines()

with open(filename) as infile:  
        line = infile.readline()
        count = 1
        while line:
            thisProfile = profile.Profile()          
            if count > 1:
                line = infile.readline()
                count += 1
            word = line.split()
            thisProfile.set_given_name(word[0])
            thisProfile.set_last_name(word[0])
            thisProfile.set_email_name(word[0])
            thisProfile.set_phone(word[0])

            ## LINE 2 -- ADDRESS
            line = infile.readline()
            count += 1
            thisProfile.set_address(line)

             ## LINE 3 -- GET FRIEND COUNT
             line = infile.readline()
             count += 1

             ## get all the friends and add them to the friends_list
             friendCount = int(line)
             thisProfile.set_number_friends(friendCount)
             friendList = []
             if friendCount > 0:
                 for allfreinds in range(0,friendCount):
                     line = infile.readline()
                     count += 1
                     friendList.append(line)
                 thisProfile.set_friends_list(friendList)

friends.txt

John Doe john.doe@hotmail.com 123456789
1 alltheway ave
1
Jane Doe
Paul Andrews paul.andrews@gmail.com 987654321
69 best street
0
Jane Doe jane.doe@facebook.com 159753456
1 alltheway ave
2
John Doe
Paul Andrews

Solution

The readline() method returns an empty string only when EOF is reached per the documentation, so you can add a condition to check if line is empty (not truthy) right after you call readline():

with open(filename) as infile:  
    while True:
        line = infile.readline()
        if not line:
            break
        thisProfile = profile.Profile()          
        word = line.split()
        thisProfile.set_given_name(word[0])

Alternatively, you can use the file object as an iterator with a for loop instead:

with open(filename) as infile:  
    for line in infile:
        thisProfile = profile.Profile()          
        word = line.split()
        thisProfile.set_given_name(word[0])


Answered By - blhsing
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I take string input for UVA online problem for java only ? Detail information needed

 October 30, 2022     arrays, eof, java, readline, user-input     No comments   

Issue

I am trying to string input for UVA online judge problem using JAVA.

like C++

while(s = getchar()) {
   if(s == EOF)
}

Solution

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string.");
String str = scanner.nextLine();

Is this what you're looking for? If you're reading from a file,

import java.io.File;

Scanner scanner = new Scanner(new File("path.txt"));
while (scanner.hasNextLine()) {
    String str = scanner.nextLine();
    //...
}


Answered By - ROBOKiTTY
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does reading a line of input from /dev/zero make my computer unresponsive?

 October 30, 2022     eof, readline, rust     No comments   

Issue

When building this code:

use std::io;

fn main() {
    let mut guess = String::new();
    let res = io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");
}

and then executing:

cargo run < /dev/zero

My computer (under Ubuntu 20) becomes unresponsive.

I have read the manual page of the readline function and this behavior doesn't seem normal.

What am I missing?


Solution

/dev/zero is a never-ending stream of NUL bytes. read_line stops when it reads a newline symbol. So, this function will never return and will try to infinitely expand the buffer. The reason your computer becomes unresponsive is likely because it starts swapping heavily, in order to accommodate the ever-growing buffer.

read_line() is definitely not what you want. Try reading a fixed amount of bytes instead?



Answered By - justinas
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, October 29, 2022

[FIXED] How to detect EOF when reading a file with readline() in Python?

 October 29, 2022     eof, exception, file, python, readline     No comments   

Issue

I need to read the file line by line with readline() and cannot easily change that. Roughly it is:

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        # I need to check that EOF has not been reached, so that readline() really returned something

The real logic is more involved, so I can't read the file at once with readlines() or write something like for line in i_file:.

Is there a way to check readline() for EOF? Does it throw an exception maybe?

It was very hard to find the answer on the internet because the documentation search redirects to something non-relevant (a tutorial rather than the reference, or GNU readline), and the noise on the internet is mostly about readlines() function.

The solution should work in Python 3.6+.


Solution

From the documentation:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

with open(file_name, 'r') as i_file:
    while True:
        line = i_file.readline()
        if not line:
            break
        # do something with line


Answered By - Barmar
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing