我得到了一个非常奇怪的计时错误,在我相信应该执行之前某些事情正在执行

时间:2013-03-12 05:33:29

标签: c file printing io

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int c, n, E, b, s, v, t, opt, valid = 0;
char current = '\0';
char previous = '\0';
FILE *fp;

/*  -n numbers lines
 *  -E appends a dollar sign to line ends
 *  -b numbers only non-blank lines
 *  -s squeezes multiple blank lines down to 1
 *  -v displays control chars, excluding tab
 *  -t includes tab in the above
 *  -e is the same as -E and -v
 */

int setFlags(int argc, char *argv[]) {
    int op;
    while ((op = getopt(argc, argv, "nEbsvte")) != -1) {
        switch (op) {
            case 'n': {
                n = 1;
                break;
            } case 'E': {
                E = 1;
                break;
            } case 'b': {
                b = 1;
                break;
            } case 's': {
                s = 1;
                break;
            } case 'v': {
                v = 1;
                break;
            } case 't': {
                t = 1;
                break;
            } case 'e': {
                E = 1;
                v = 1;
                break;
            } case '?': {
                //fprintf(stderr, "Option `-%c` is not valid.\n", optopt);
                return EXIT_FAILURE;
            } default: {
                abort();
            }
        }
    }
    opt = optind;

    if(n == 1) {
        b = 0;
    }

    return EXIT_SUCCESS;
}

int checkFile(char *path) {
    if (access(path, R_OK) == 0) {
        return EXIT_SUCCESS;
    } else {
        fprintf(stderr, "cat: %s: %s\n", argv[i], strerror(errno));
        errno = 0;
        return EXIT_FAILURE;
    }
}

int doPrint(char *path) {
    if (strcmp(path, "stdin") == 0) {
        fp = stdin;
    } else {
        if (checkFile(path) == 1) {
            return EXIT_FAILURE;
        } else {
            fp = fopen(path, "r");
        }
    }
    while ((c = fgetc(fp)) != EOF) {
        putchar(c);
    }
    fclose(fp);
    return EXIT_SUCCESS;
}

int main (int argc, char *argv[]) {
    if (setFlags(argc, argv) == 1) {
        fprintf(stderr, "The program has terminated with an error.\n"
        "An invalid option was specified.\n");
        return EXIT_FAILURE;
    } else {
        if ((argc - opt) == 0) {
            doPrint("stdin");
        } else {
            for(int i = opt; i < argc; i++) {
                doPrint(argv[i]);
            }
        }
    }
}

我收到一个非常疯狂的错误,我的程序在完成文件内容的写入之前输出checkFile中的错误行(在结束之前总是一次聊天)。

这让我感到疯狂,无论我在哪里移动那段代码,它都无法按预期工作。

我确定答案可能是微不足道的,但它让我难过。在输出完成之前我甚至会在睡眠和各种其他事情中抛出,它会抛出错误,然后睡觉,然后打印最后一个角色。

任何帮助?

1 个答案:

答案 0 :(得分:2)

使用printf时,默认情况下会缓存stdout输出。这意味着它可以与其他输出交错,通常来自stderr。默认情况下,stderr是无缓冲的,以便在发生错误时立即打印输出。

可以通过明智地使用fflush或使用stdout关闭setbuf的文件缓冲来解决交错问题。请务必阅读setbuf的手册页,因为有一些警告。

在这种情况下,在doPrint函数末尾添加fflush(stdout)可以解决“问题”。