0

我需要使用此函数将数据块读入文件缓冲区并有效地执行此操作。对我的函数的调用需要从缓冲区返回下一个字符,或者读取一个新的数据块并从该新块返回第一个字符。这是我到目前为止所拥有的。任何帮助,将不胜感激。

int get_next_char(int fd)   {

    static char file_buffer[FILE_BUFFER_SIZE];
    static int next;
    static int i= 0;

    while((next = read( fd,&file_buffer, FILE_BUFFER_SIZE)) > 0) {
        // next equals number of chars actually read from fd
        while(i < next) i++;
    }

    if( next  == -1 || next== '\0') {
        return EXIT_FAILURE;
    } else {
        return file_buffer[i];
    }
}
4

1 回答 1

1

fgetc您可以为此使用系统调用实现自己的内部缓冲版本。一些微不足道的事情如下:

#define BUF_SIZE 1024

int fgetc_impl(FILE* fp) {
    static FILE *pBuffered;
    static char buffer[BUF_SIZE];
    static int start = 0, end = 0;

    // conditions under which you'll need to make a syscall to read into
    // the local buffer. Either a new file descriptor has been presented, or
    // we've read to the end of the local buffer and need to re-read a new chunk into it
    if (pBuffered != fp || start == end) {
        pBuffered = fp;
        end = read((int)fp, buffer, BUF_SIZE);
        start = 0;

        // mask the syscall failure and report it as an EOF, change this behaviour if you want.
        if (end < 0) {
            end = 0; 
        }
    }

    // return EOF if the syscall to read failed, or couldn't read any more data from the file descriptor.
    return end == 0 ? EOF : buffer[start++];
}

简单的用法如下:

FILE *fp = fopen("test.txt", "r");
int c = 0;
while ( (c = fgetc_impl(fp)) != EOF ) {
    printf("%c", (char)c);
}
fclose(fp);
于 2013-03-20T02:44:45.120 回答