File: fgets.c

package info (click to toggle)
icmake 6.30-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,360 kB
  • ctags: 1,415
  • sloc: ansic: 7,727; makefile: 1,465; sh: 244; asm: 126; cpp: 39
file content (55 lines) | stat: -rw-r--r-- 1,366 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
\funcref{fun\_fgets}{void fun\_fgets ()}
    {}
    {}
    {}
    {fun\_gets(), fun\_printf(), fun\_fprintf()}
    {funfgets.c}
    {

        This function reads in a string from a file and returns it in the {\em
        reg} return register as an {\em e\_str} value. The arguments on the
        stack are: the filename and an {\em int offset}, where the read
        operation should start.

        The return value is a list, holding as the first list element the read
        string and as the second element the offset where the reading operation
        ended. The offset and the string are empty (offset 0, string "") when
        the reading operation failed.

    }
*/

#include "builtin.ih"

void fun_fgets()
{
    char const *filename = stringStr(top());
    size_t offset = intValue(top() - 1);
    FILE *inf;

    reg = listConstructor();

    if 
    ( 
        (inf = fopen (filename, "r"))
        &&
        fseek(inf, (long)offset, SEEK_SET) == 0     /* locate the read-pos. */
    )
    {
        char *dest = getLine(inf);

        if (dest)                               /* anything read?           */
        {
            char buffer[20];     
            sprintf (buffer, "%d", (int)ftell(inf));

            listAdd_cP(&reg, dest);
            listAdd_cP(&reg, buffer);

            free(dest);
        }
        fclose (inf);
    }
}