Java: how to abort a thread reading from System.in

Heinz Kabutz’s newsletter shows how to abort System.in reads: import java.io.*; import java.util.concurrent.*; class ConsoleInputReadTask implements Callable<String> { public String call() throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println(“ConsoleInputReadTask run() called.”); String input; do { System.out.println(“Please type something: “); try { // wait until we have data to complete a readLine() while … Read more

Is close/fclose on stdin guaranteed to be correct?

fclose(stdin) causes any further use of stdin (implicit or explicit) to invoke undefined behavior, which is a very bad thing. It does not “inhibit input”. close(fileno(stdin)) causes any further attempts at input from stdin, after the current buffer has been depleted, to fail with EBADF, but only until you open another file, in which case … Read more

ungetc: number of bytes of pushback

The C99 standard (and the C89 standard before that) said unequivocally: One character of pushback is guaranteed. If the ungetc function is called too many times on the same stream without an intervening read or file positioning operation on that stream, the operation may fail. So, to be portable, you do not assume more than … Read more

Tried and true simple file copying code in C?

This is the function I use when I need to copy from one file to another – with test harness: /* @(#)File: $RCSfile: fcopy.c,v $ @(#)Version: $Revision: 1.11 $ @(#)Last changed: $Date: 2008/02/11 07:28:06 $ @(#)Purpose: Copy the rest of file1 to file2 @(#)Author: J Leffler @(#)Modified: 1991,1997,2000,2003,2005,2008 */ /*TABSTOP=4*/ #include “jlss.h” #include “stderr.h” #ifndef … Read more

ftell at a position past 2GB

on long int long int is supposed to be AT LEAST 32-bits, but C99 standard does NOT limit it to 32-bit. C99 standard does provide convenience types like int16_t & int32_t etc that map to correct bit sizes for a target platform. on ftell/fseek ftell() and fseek() are limited to 32 bits (including sign bit) … Read more

How can one flush input stream in C?

fflush(stdin) is undefined behaviour(a). Instead, make scanf “eat” the newline: scanf(“%s %d %f\n”, e.name, &e.age, &e.bs); Everyone else makes a good point about scanf being a bad choice. Instead, you should use fgets and sscanf: const unsigned int BUF_SIZE = 1024; char buf[BUF_SIZE]; fgets(buf, BUF_SIZE, stdin); sscanf(buf, “%s %d %f”, e.name, &e.age, &e.bs); (a) See, … Read more

whitespace in the format string (scanf)

Whitespace in the format string matches 0 or more whitespace characters in the input. So “%d c %d” expects number, then any amount of whitespace characters, then character c, then any amount of whitespace characters and another number at the end. “%dc%d” expects number, c, number. Also note, that if you use * in the … Read more