Welcome, guest | Sign In | My Account | Store | Cart

redirect printf, stdout,stderr

C, 29 lines
 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
int openlog()
{

    int fd = open(LOG,O_RDWR | O_APPEND |O_CREAT, 0666);
    if (-1 == fd)
    {
        eyou_syslog("open eyoucron log failed : %s\n", strerror(errno));
        return -1;
    }

    if( -1 == dup2(fd, STDOUT_FILENO)){
        eyou_syslog("dup stdout failed : %s\n", strerror(errno));
        goto openerr;
    }

    if( -1 == dup2(fd, STDERR_FILENO)){
        eyou_syslog("dup stderr failed : %s\n", strerror(errno));
        goto openerr;
    }

    if( -1 == setvbuf(stdout, NULL, _IOLBF, 0)){
        eyou_syslog("set lined-buffer for log failed : %s\n", strerror(errno));
        goto openerr;
    }
    return 0;

openerr:
    return -1;
}

1 comment

Robert Naiditch 14 years, 9 months ago  # | flag

I haven't seen unstructured code such as this in 20 years. This is a poor design. It is never acceptable to use a goto and it is lazy on top of it. The usage of magical numbers (-1) is also unacceptable. I understand this is free and what am I complaining about anyway. That aside, it is not a good style. I would hate to have a novice of C to ever view this code and think this is the way to write professional C, something I have done since 1983.

Created by J Y on Thu, 2 Jul 2009 (MIT)
C recipes (32)
J Y's recipes (21)

Required Modules

  • (none specified)

Other Information and Tasks