root/NEWT0/trunk/sample/nsof.newt

Revision 53, 1.3 kB (checked in by gnue, 3 years ago)

- cleaned up a warning
- the symbols for seek are now seek_set, seek_cur and seek_end since end conflicted with end keyword
- got seek to actually work (replaced == with NewtRefEqual, removed quotes for the symbols)
- added getc, putc and write (write writes a binary just like read reads a binary)
- added a sample code for NSOF I/O.

contribute patch by Paul Guyot

Line 
1#!newt
2
3Require("protoFILE");
4Require("NativeCalls");
5
6DefGlobalFn('GetWalterSmithStructure, func ()
7begin
8    x := {name: "Walter Smith",
9        cats: 2,
10        bounds: {left: 10, top: 14, right: 40, bottom: 100},
11        uChar: $\u2022,
12        phones: ["408-996-1010", nil]};
13    x.phones[1] := SetClass("408-974-9094", 'faxPhone);
14    x.nameAgain := x.name;
15    return x;
16end );
17
18// This function gets the size of a file using ftell(3)
19// It takes an open file (based on protoFILE).
20DefGlobalFn('GetFileSizeUsingTell, func (file)
21begin
22    local pos := file:tell();
23    file:seek(0, 'seek_end);
24    local size := file:tell();
25    file:seek(pos, 'set);
26    return size;
27end );
28
29local path := "/tmp/test.nsof";
30
31// Transform into NSOF and back the Walter Smith sample structure.
32local file := {_proto: @protoFILE};
33file:open(path, "w");
34local binary := MakeNSOF(GetWalterSmithStructure(), 2);
35file:write(binary);
36file:close();
37
38// Open the file again, for reading.
39file := {_proto: @protoFILE};
40file:open(path, "r");
41local size := GetFileSizeUsingTell(file);
42binary := file:read(size);
43local frame := ReadNSOF(binary);
44P(frame);
45
46// Delete the file using NativeCalls.
47local libc := OpenNativeLibrary("libc");
48
49libc:DefineGlobalFn({
50    name: "unlink",
51    symbol: '|libc.unlink|,
52    args: ['string],
53    result: 'sint32});
54|libc.unlink|(path);
55
56libc:Close();
57
58true;
Note: See TracBrowser for help on using the browser.