我需要使用此函数将一块数据读入文件缓冲区,并有效地执行此操作。对函数的调用需要从缓冲区返回下一个字符,或者读取新的数据块并从新块返回第一个字符。这是我目前所拥有的。任何帮助都将不胜感激。
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];
}
}
最佳答案
您可以使用系统调用实现自己的内部缓冲版本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);