char *readLine() {
int bufSize = 1024;
static char *buf = malloc(sizeof(char) * (1 + bufSize));
static int bytesAfterNewLine = 0; // number of bytes left from last call
static int lastpos = 0; // where the leftover starts
int totalBytes = 0; // total number of bytes in the array
int foundLineBreak = 0;
if (bytesAfterNewLine != 0) {
memmove(buf, buf + lastpos, bytesAfterNewLine);
totalBytes = bytesAfterNewLine;
lastpos = 0;
}
while (true) {
for (; lastpos < totalBytes; ++lastpos) {
if (buf[lastpos] == '\n') {
buf[lastpos] == '\0';
bytesAfterNewLine = totalBytes - lastpos - 1;
foundLineBreak = 1;
lastpos = (last + 1) % bufSize;
break;
}
}
if (foundLineBreak) break;
if (bufSize == totalBytes) {
bufSize *= 2;
buf = realloc(buf, bufSize + 1);
}
int bytes = 0;
while (true) {
bytes = read(buf + totalBytes, bufSize - totalBytes);
if (bytes != 0) break;
}
if (bytes == -1) {
buf[totalBytes] = '\0';
break;
}
totalBytes += bytes;
}
if (totalBytes == 0 && foundLineBreak == 0) {
return NULL:
} else {
return buf;
}
}
Sunday, February 19, 2012
implement readLine using read
Sunday, November 28, 2010
printf cheatsheet
Format string
% [flag]* [minimum_field_width] [precision] [length_modifier] <conversion_specifier>
Flags
| Flag | Description | |
| # | The value should be converted to an "alternate form". | |
| 0 | zero padded. By default, blank padded | |
| - | left adjusted | |
| ' ' | (A single space) A blank should be left before a positive number (or empty string) produced by a signed conversion. | |
| + | A sign is always placed before a number produced by a signed conversion. |
Minimum Field Width
"a decimal digit string (with non-zero first digit). If the value has fewer characters, it will be padded. In no case does a nonexistent or small field width cause truncation of a field."
Precision
a period ('.') followed by an optional decimal digit string. It has different meanings for different conversions.
| Precision | Description | |
| d, i, o, u, x, and X | minimum number of digits to appear | printf("%.2d", 1) ==> "01" |
| a, A, e, E, f, and F | number of digits to appear after the radix character | printf("%.2f",0.1) ==> "0.10" |
| g and G | maximum number of significant digits | |
| s and S | maximum number of characters to be printed from a string | printf("%.2s","hello") ==> "he" |
Length Modifier
For each conversion specifier, there is expected argument type. For example, for conversion d, and i, type of arguments should be int. Length Modifiers can be used to specify argument types rather than expected type by default.
| Modifier | Conversion | Argument types |
| hh | d, i, o, u, x, or X | signed char or unsigned char |
| n | signed char* | |
| h | d, i, o, u, x, or X | short int or unsigned short int |
| b | short int* | |
| l | d, i, o, u, x, or X | long int, or unsigned long int |
| n | long int* | |
| c | wint_t | |
| s | wchar_t | |
| ll | d, i, o, u, x, or X | long long int, or unsigned long long int |
| n | long long int* | |
| L | a, A, e, E, f, F, g, or G | long double |
| j | d, i, o, u, x, or X | intmax_t, uintmax_t |
| z | d, i, o, u, x, or X | size_t, ssize_t |
| t | d, i, o, u, x, or X | ptrdiff_t |
Conversion specifier
| conversion | arguments | notation | |
| d, i | int argument | signed decimal notation | |
| o, u, x, X | unsigned int | unsigned octal, unsigned decimal, unsigned hexdec notation | abcedf are used for x. ABCDEF are used for X. |
| e, E | double | rounded and converted in the style [-]d.ddde±dd | precision is 6 by default. |
| f, F | double | rounded and converted to decimal notation in the style [-]ddd.ddd | precision is 6 by default. |
| g, G | double | converted in style f or e (or F or E for G conversions). Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. | |
| a, A | double | converted to hexadecimal notation. for a, (using the letters abcdef) in the style [-]0xh.hhhhp±d; | C99; not in SUSv2 |
| c | int | converted to an unsigned char, and the resulting character is written | |
| s | const char* | Characters from the array are written. | |
| p | void * | printed in hexadecimal (as if by %#x or %#lx) | |
| n | int * | The number of characters written so far is stored into the integer indicated by the int * (or variant) pointer argument. |
Tuesday, December 22, 2009
Interesting “Epigrams on Programming”
Recently I found this
Epigrams on Programming: http://www.pam1.bcs.uwa.edu.au/~michaelw/Perlis_Epigrams.html
Really interesting, terse and helpful. Among those epigrams, I like following ones a lot
- Programming is an unnatural act.
- Computer Science is embarrassed by the computer.
- In man-machine symbiosis, it is man who must adjust: The machines can't.
Thursday, August 28, 2008
Ruby notes(2) - OO
Function
Definitiondef method([arg1, ..., argn,..., *arg, &arg])Singleton Method
statements
end
def obj.method([arg1, ..., argn,..., *arg, &arg])
statements [rescue [exception [, exception...]] [=>var] [then] code ]... [else code ] [ensure code] end
undef method #make the method undefined.yield(expr...) #execute the block passed in to current method.super(expr...) #execute the method in super class.super #execute the method in super class with current method's arguments are passed in.
yieldalias newmethodname oldmethodname
Method Invocation
(*) General
method ([param1 ...[, *param [, ¶m]]])
method [param1 ...[, *param [, ¶m]]]
obj.method([param1 ...[, *param [, ¶m]]])
obj.method [param1 ...[, *param [, ¶m]]])
obj::method([param1 ...[, *param [, ¶m]]])
obj::method [param1 ...[, *param [, ¶m]]]
(*) With blocks
methdo { |[var1 [, var2 ...]]|
code
}
method do |[var1 [, var2 ...]]|
code goes here
end
A block has its own local scope and code within a block can access local variables of outer scope.
Class
Definitionclass classname [ < superclass]
code
end
classname MUST be a constant instead of a global or local variable. Class definition introduces a new scope. In order for different definitions of the same class to be merged, one of the two conditions must be met:
(1) A class does not include superclass
(2) if a class definition includes superclass, superclass MUST match super class of previous declaration.
class << object
code
end
Creation
Instances of a class are created by using method new. str = String.new or str = String::new
Modules
Definitionmodule modulename
code
endmodulename MUST be a constant instead of a global or local variable. Module definition introduces a new scope. Different definitions of the same module are merged.
Sunday, August 24, 2008
Ruby notes-basic(1)
Semicolons and newline characters are interpreted as ending of a statement. +, = or \ can be use as line continuation characters.
Comments
Single-line comments: Comments extend from # to the end of a line.
Multi-line comments:
=beginNote: '=begin' and '=end' must appear at the beginning of a line.
comments go here
=end
Integer literals: 123, 0123(octal), 0xf34(hex), 0b1123(binary), ?d(char code for 'd')
Float-point literals: 23.45, 3e4, 4E10, 5e+39
String literals:
double quotations: allow substitution and escape character sequences.
single quotations: don't allow substitution and escape character sequences except \\ and \'.
Adjacent strings are concatenated automatically. "abc""def" => "abcdef"
Command execution: `command`. The syntax is similar to the counterpart of bash. It allows substituion and escape character sequences. The output generated by execution of the command is converted to a string.
here documents:
| <<EOF content goes here EOF |
The string is in double quotations. |
| <<"EOF" content goes here EOF |
|
| <<'EOF' content goes here EOF |
The string is in single quotations. |
| <<`EOF` command goes here EOF |
The string is in back quotes. |
| <<-EOF command goes here EOF |
The delimiter ('EOF' in this example) needs not be at the beginning of a line. |
Symbols:
"A symbol is an object corresponding to an identifier or variable"
:name #symbol for 'name'
:$name #symbol for variable 'name'
Array
[], [1,2,3], [1,[2,3]]
%w(str1 str2 str3) => ["str1", "str2", "str3"]
Dictionary(Map, or Hash):
{key => value}
Regular expression:
/pattern/
/pattern/options
Alternatives:
%!string! and %Q!string! are equivalent to "string".
%q!string! is equivalent to 'string'
%x!command! is equivalent to `command`.
%r!pattern!
Variable
| Type | Description | Example | Note |
| global variables | can be accessed globally by and program. | $var | Uninitialized global variables are set to nil. |
| instance | variables that belong to an object. | @var | |
| class | variables that belong to a class. | @@var | Class variables must be initialized before they are accessed in methods. |
| contants | Constants as you know in other languages | Var | must begin with an upper case letter.May not be defined in methods. |
| local | Local variables. | var | must begin with a lowercase letter or _ |
Variable substitutions: #{varname}. E.g. #{filename}, #{@conf}, #{$stdin}
Variable assignments
var = value
var1, var2, ..., *varn = expr1, expr2, ..., *exprn
Operators:
expr?expr1:expr2The same as the tertiary operator in C/C++.
defined? varname#return a description about the variable/method or nil.
Control statements
| Name | Syntax | Alternatives |
| if | if cond [then] code [elsif cond [then] code] [else code] end |
code if cond |
| unless | unless cond [then] code [else code] end |
code unless cond |
| case | case expr [when expr [,expr ...] [then] code ]... [else code] end |
|
| while | while cond [do] code end |
(1)code while cond (2)begin code end while cond. Note: code is executed once before cond is evaluated. |
| until | until cond [do] code end |
(1) code until cond (2) begin code end until cond Note: code is executed once before cond is evaluated. |
| for | for var[, var2 ...] in expr [do] code end |
expr do |var [,var...]| code end |
| break | Break from look | |
| next | like continue in C++ | |
| redo | re-execute the loop body once without evaluation of conditional expression. | |
| retry | re-execute a call to a method | |
| begin | begin code [rescue [exception_class [, excep_cls...]] [=>var] [then] code ]... [else code ] [ensure code ] end |
Code in ensure clause is always executed. Code in else clause is executed only when no exceptions are raised. Code in rescue clause is executed when exception is caught. |
| rescue | code rescue expr | Evaluate the expr only if an exception is caught. |
| raise | raise exception_class, message raise exception_object raise message raise |
Raise an exception. To call raise in a rescue clause will re-raise the exception. |
| BEGIN | BEGIN{ code } |
Code to be executed before the program is run. |
| END | END{ code } |
Code to be executed when the interpreter quits. |
Saturday, August 09, 2008
API design
Many times I struggled with API design dilemma which I didn't know how to solve perfectly. As all know, API design is important. However, it is difficult to get it right. Actually, nothing is absolutely right or wrong. What matters is tradeoff. I googled and found a pretty good article (written by Michi Henning from ZeroC) which give insight about API design. The article is here.
I agree with most of the author's viewpoints. Here I just would like to outline the elaborate article. Most following content is from the article. Gradually, I will add my own viewpoints and guidelines about how to design good API.
The effect of bad-designed API:
"Even minor and quite innocent design flaws have a tendency to get magnified out of all proportion because APIs are provided once, but are called many times. If a design flaw results in awkward or inefficient code, the resulting problems show up at every point the API is called. In addition, separate design flaws that in isolation are minor can interact with each other in surprisingly damaging ways and quickly lead to a huge amount of collateral damage.
The lower in the abstraction hierarchy an API defect occurs, the more serious are the consequences."
How to design good API:
"(1) APIs should be designed from the perspective of the caller.
APIs should be documented before they are implemented.
(2) An API must provide sufficient functionality for the caller to achieve its task.
(3) An API should be minimal, without imposing undue inconvenience on the caller.
(4) APIs cannot be designed without an understanding of their context.
(5) General-purpose APIs should be "policy-free;" special-purpose APIs should be "policy-rich."
(6) Good APIs don't pass the buck.
(7) Good APIs are ergonomic. "
Tuesday, July 22, 2008
Bash cheat sheet
Part of content in this post is from other web sites, mainly from Bash manual. Because all formal documents and introduction books are long and too detailed , I just list some key points and usage examples so that later I can quickly remember a bash feature by reading this post instead of the whole bash manual.
[Bash switch]
First, get a list of installed shells: chsh -l or cat /etc/shells.
Then use chsh -s to change your default shell. It modifies file /ect/passwd to reflect your change of shell preference.
[Output]
[echo] Output the arguments. If -n is given, trailing newline is suppressed. If -e is given, interpretation of escape characters is turned on.
[Output redirection]
> output redirection
"Code can be added to a program to figure out when its output is being redirected. Then, the program can behave differently in those two cases—and that’s what ls is doing." This means what you see on screen may be different from content of the file to which you redirect the output. For command ls, use ls -C>file.
command 1 > file1 2 > file2
1: stdout; 2: stderr; 1 is the default number.
command >& file
command &> file
command > file 2>&1
These three commands redirect stdout and stderr to the same file.
The tee command writes the output to the filename specified as its parameter and also write that same output to standard out.
>> append
[Input]
< input
<< EOF here-document.
"all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion.”
<< \EOF or << 'EOF' or <<E\OF
When we escape some or all of the characters of the EOF, bash knows not to do the expansions.
<<-EOF
The hyphen just after the << is enough to tell bash to ignore the leading tab characters so that you can indent here-document. This is for tab characters only and not arbitrary white space.
use read to get input from user.
[Command execution]
get exit status of last executed command using $? (0-255).
(1) command1 & command2 & command3 //execute commands independently
(2) command1 && command2 && command3 //execute commands sequentialy
(3) command1 || command2
(4) command_name&
If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. The shell does not wait for the command to finish, and the return status is 0 (true)
(5) nohup - run a command immune to hangups, with output to a non-tty
(6) command1; command2;
Commands separated by a ‘;’ are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.
(7) $( cmd ) or `cmd`: execute the command and return the output.
(8) $(( arithmetic_op )): do arithmetic operation and return the output.
[Pipe]
Each command in a pipeline is executed in its own subshell.
[Group commands]
{ comamnd1; command2; } > file //use current shell environment
( command1; command2; ) >file //use a subshell to execute grouped commands
[Variables]
Array variable: varname=(value1, value2); use ${varname[index]} to access an element.
Type of all variables is string. And sometimes bash operators can treat the content as other types.
Assignment: VARNAME=VALUE //Note: there is not whitespace around equal sign.Or else bash interpreter
//can not distinguish between variable name and command name. So it will
//VARNAME as a command name.
Get value: $VARNAME //the dollar sign is a must-have.
Use full syntax(braces) to separate variable name from surrounding text:
E.g. ${VAR}notvarname
export can be used to export a variable to environment so that it can be used by other scripts.
export VAR=value
Exported variables are call by value. Change of variable value in called script does not affect original value in calling script.
Use command set to see all defined variables in the environment
Use command env to see all exported variables in the environment.
${varname:-defaultvalue}: if variable varname is set and not empty, return its value; else return defaultvalue.
${varname:=defaultvalue}: similar to last one except that defaultvalue is assigned to variable varname if the variable is empty or not set. varname can not be positional variables(1, 2, ..., *)
${varname=defaultvalue}: Assignment happens only when variable varname is not set.
${varname:?defaultvalue}: If varname is unset or empty, print defaultvalue and exit.
Parameters passed to a script can be retrieved by accessing special variables: ${1},${2}...
Use variable ${#} to get number of parameters.
Command shift can be used to shift the parameters: The positional parameters from $N+1 ... are renamed to $1 ... If N is not given, it is assumed to be 1.
[Special variables]
Variable $* can be used to get all parameters. If a certain parameter contains blank, use "$@".
E.g. command "param1" "second param"
value of $* or $@: param1 second param
value of "$@": "param1" "second param"
value of "$*": "param1 second param"
Always use "$@" if possible! And always use "${varname}"(include double quotes) to access value of the variable.
If a parmeter contains blanks, use double quotes to retrieve the value.
ls "${varname}" instead of ls ${varname}.
${#}: Expands to the number of positional parameters in decimal.
${-}: (A hyphen) Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).
${$}: Expands to the process id of the shell. In a () subshell, it expands to the process id of the invoking shell, not the subshell.
${!}: Expands to the process id of the most recently executed background (asynchronous) command.
${0}: Expands to the name of the shell or shell script. This is set at shell initialization.
[Misc]
(1) ${#var}: return length of the string
# character denotes start of a comment.
(2) Long comment: use "do nothing(:)" and here-document.
E.g.
:<<EOF
doc goes here
EOF
[Quotation]
Unquoted text and double quoted text is subject to shell expansion.
(1) In double quoted text, '\' can be used to escape special characters. Backslashes preceding characters without a special meaning are left unmodified.
(2) Single quoted text is not subject to shell expansion. So you can not use escape sequence in single quoted text. So text 'use \' in single quoted text' is incorrect. It also means you can not include a single quote inside single quoted text, even if using a '\'. You can escape a single quote outside of surrounding single quotes.
(3) Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. The expanded result is single-quoted, as if the dollar sign had not been present.
[Function/Command scope]
If you want to enforce using of an external command instead of built-in command, use enable -n. Or you can use command command, which ignores shell functions.
E.g. enable -n built-in-function
command command_name
[Control structures and more]
(1) until test-command; do statements; done
(2) while test-command; do statements; done
(3) for var in words; do statements; done
(4) for ((expr1; expr2; expr3 )); do statements; done
(5) if test-commands; then statements;
elif test_commands2; then statements;
else statements;
fi
(6) case word in
pattern) statements;;
pattern2|pattern3) statements;;
*) statements;;
esac
(7) select var in words; do statements; done
The commands are executed after each selection until a break command is executed, at which point the select command completes.
(8) (( arithmetic_expression))
If the value of the expression is non-zero, return status is 0; otherwise return status is 1. This is equivalent to
let "expression".
(9)[[ ]]
[Shell expansions]
(1) Brace expansion (note: ${...} is not expanded)
a{b,c,d}e => abd ace ade
(2) Tilde expansion
~: value of $HOME
~username: home directory of user username.
~+: $PWD
~-: $OLDPWD
~N: equivalent to 'dirs +N'
~-N: equivalent to 'dirs -N'
(3) Parameter expansion
(4) Command substitution
$(command) or `command`: executs command and replaces the command substitution with the standard output of the command with any trailing newlines deleted.
(5) Arithmetic expansion
$(( expression )): allows the evalution of an arithmetic expression and substitution of the result.
(6) Process substitution
Actually I don't understand it much.
(7) Word splitting
"The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting."
(8) Filename expansion
"After word splitting, unless the -f option has been set (see The Set Builtin), Bash scans each word for the characters ‘*’, ‘?’, and ‘[’. If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of file names matching the pattern."
[Useful commands]
(*) customize shell promote
set environment variable "PS1"
(*) How to find commands?
Try following commands:
[type]
a bash command. Searches files in the PATH, aliases, keywords, functions, built-in commands...
[which]
displays the full path of the executables that would have been executed when this argument had been entered at the shell prompt(just searches files in $PATH).
[apropos]
search the whatis database for strings(same as man -k)
[locate, slocate]
reads one or more databases prepared by updatedb and writes file names matching at least one of the PATTERNs to standard output. Location of the actual database varies from system to system.
[whereis]
locate the binary, source, and manual page files for a command. An entry is displayed only when the whole searched word is matched(not a substring of a long word).
[find]
search for files in a directory hierarchy.
(*) Info about a command
[man]:
display manual of the command;
[help]:
display information of bash built-in commands. For a bash build-in command, if you use man command to display its information, you will get a large bash manual.
[info]:
display Info doc of an arbitrary command.
(*) Get information about a file
[ls]
List information about the FILEs (the current directory by default). You can either list directory contents of get information about a file(a regular file, not directory).
E.g.
ls -a .* //list all files name of which startes with a .? no!!! Bash will expand pattern .* at first. So
// ls .. is included which causes content of parent directory is displayed. And so on and so on.
// You can use echo command to see what the pattern is expanded to. E.g. echo .*
ls -d .* //-d switch enforce ls to list directory entries instead of contents.
[stat]
Display file or file system status.
[find]
E.g. find /path/ -name file_name -printf '%m %u %t'
[file]
determine file type. There are three sets of tests, performed in this order: filesystem tests, magic number tests, and language tests.
Tuesday, July 01, 2008
"Hello World" Programs in different languages
Every time when we learn a new programming language, the first program is always to output "Hello World".
Someone collects "Hello World" programs written in hundreds of different languages. Check out :http://www.ntecs.de/old-hp/uu9r/lang/html/lang-all.en.html
Monday, June 30, 2008
Change font in PDT
The way to change font in PDT is not intuitive. PDT does not support configuration of font itself. Instead, it inherits global configuration. By click "windows->preference->Apperance->Colors and Fonts", you will get:
Although there are two entries related to PHP, they are useless in fact. You can not configure them. Instead, you may think configuration of entry "Basic" should work. But, you are wrong. You should configure entry "Structured Text Editors" to configure fonts which will be used by PDT PHP editor. I don't why PDT chooses to inherit font setting from "Structured Text Editors".
Saturday, May 03, 2008
Differences of array and pointer in C/C++
(1) Array
int main(){
char *p = "hello,world";
char *p2 = "hello,worldc";
char str[] = "hello,world";
char str2[] = "hello,world"; printf("%x %x %x %x\n", p, p2, str, str2);
}
Sample output(compiled with GCC 4.1.2 on Ubuntu 6.06.1LTS):
804856c 8048578 bf879674 bf879668
Conclusions:
<1> Strings pointed by pointers p and p2 are allocated in different places from strings of str and str2. The first and second strings are allocatd to static memory area and these two strings can not be modified. So the following statement makes the program crash(run time error instead of compilation time):
p[0] = 'd'
The third and fourth strings are allocated on stack. They can be modified. They just exist in current function call and after this function is executed they are discarded and should not be referenced any more.
<2> Pointers can be modified arbitrarily while array variables can not be modified.
Following code is illegal:
char str[] = "hello,world";
char str2[] = "abcdefgh";
str = str2; //illegal, can not be compiled successfully.
str++; //illegal
str+1; //legal, just like an ordinary addition.
In other words, array name is a reference to an array and it represents the array. It is kind of a contant.
<3> Array name cannot be used a left value. Array name can be used as pointer if it acts as right value. Pointer can not be cast to array!!!
<4> Apply sizeof to array name, you will get size of the array. Apply sizeofi to a pointer, you will get size of the pointer(generally, four bytes).
<5> Array must be initialized and corresponding memory is allocated.
<6> void function(type array[]) is equivalent to void function(type *pointer).
数组要么在静态存储区被创建(如全局数组),要么在栈上被创建。数组名对应着(而不是指向)一块内存,其地址与容量在生命期内保持不变,只有数组的内容可以改变。
指针可以随时指向任意类型的内存块,它的特征是“可变”,所以我们常用指针来操作动态内存。指针远比数组灵活,但也更危险。
不能对数组名进行直接复制与比较。示例7-3-2中,若想把数组a的内容复制给数组b,不能用语句 b = a ,否则将产生编译错误。
当数组作为函数的参数进行传递时,该数组自动退化为同类型的指针.
对数组名sizeof()得到的是数组所占的大小,而对指针sizeof()得到的是指针内容所占的字节数。
数组定义时必须初始化并分配空间,而指针定义时可以不初始化。
如果将数组或指针作为自定义函数的形参,此时数组名和指针完全等价.在函数体内可以用数组名进行自增或赋值等运算,因为在一般的编译程序中,将函数的形参数组编译成指针.既f(char Data[])====>f(char *Data)
