有没有办法在 C 中使用 fgetc 转到文件的开头和指定的索引处?
Is there a way to go to the beginning of a file and at a specified index with fgetc in C?
对于我的算法,我想在遍历文件中的所有字符后回溯到特定的索引字符。例如,我有一个包含 ABCDEF
的文件,我想按顺序访问 ABCDEF
然后 BCDEF
然后 CDEF
等等。有没有一种方法可以只使用 fgetc 而不使用字符串缓冲区?
FILE *file = fopen("temp.txt", "r");
int c;
while (1) {
c = fgetc(file);
if (feof(file)) {
break;
}
// Access and print char
}
您可能希望比这更干净地处理边缘情况和错误,但是...:[=11=]
#include <stdio.h>
#include <stdlib.h>
FILE *
xfopen(const char *path, const char *mode)
{
FILE *fp = path[0] != '-' || path[1] != '[=10=]' ? fopen(path, mode) :
*mode == 'r' ? stdin : stdout;
if( fp == NULL ) {
perror(path);
exit(EXIT_FAILURE);
}
return fp;
}
int
main(int argc, char **argv)
{
int c;
long offset = 0;
FILE *ifp = argc > 1 ? xfopen(argv[1], "r") : stdin;
while( fseek(ifp, offset++, SEEK_SET) == 0 ) {
while( (c = fgetc(ifp)) != EOF ) {
putchar(c);
}
if( ferror(ifp) ) {
return EXIT_FAILURE;
}
if( offset == ftell(ifp) ) {
break;
}
}
return EXIT_SUCCESS;
}
对于我的算法,我想在遍历文件中的所有字符后回溯到特定的索引字符。例如,我有一个包含 ABCDEF
的文件,我想按顺序访问 ABCDEF
然后 BCDEF
然后 CDEF
等等。有没有一种方法可以只使用 fgetc 而不使用字符串缓冲区?
FILE *file = fopen("temp.txt", "r");
int c;
while (1) {
c = fgetc(file);
if (feof(file)) {
break;
}
// Access and print char
}
您可能希望比这更干净地处理边缘情况和错误,但是...:[=11=]
#include <stdio.h>
#include <stdlib.h>
FILE *
xfopen(const char *path, const char *mode)
{
FILE *fp = path[0] != '-' || path[1] != '[=10=]' ? fopen(path, mode) :
*mode == 'r' ? stdin : stdout;
if( fp == NULL ) {
perror(path);
exit(EXIT_FAILURE);
}
return fp;
}
int
main(int argc, char **argv)
{
int c;
long offset = 0;
FILE *ifp = argc > 1 ? xfopen(argv[1], "r") : stdin;
while( fseek(ifp, offset++, SEEK_SET) == 0 ) {
while( (c = fgetc(ifp)) != EOF ) {
putchar(c);
}
if( ferror(ifp) ) {
return EXIT_FAILURE;
}
if( offset == ftell(ifp) ) {
break;
}
}
return EXIT_SUCCESS;
}