Search code examples
cfgetc

Is there a way to go to the beginning of a file and at a specified index with fgetc in C?


For my algorithm, I would like to backtrack after going through all the chars in a file back to specific index char. For example, I have a file with ABCDEF, I want to access in the order ABCDEF then BCDEF then CDEF and so on. Is there a way I can do that with just fgetc and no string buffer?

  FILE *file = fopen("temp.txt", "r");
  int c;  
  while (1) {
    c = fgetc(file);
    if (feof(file)) {
      break;
    }
  // Access and print char
  }

Solution

  • You'll probably want to handle edge cases and error more cleanly than this, but...:

    #include <stdio.h>
    #include <stdlib.h>
    
    FILE *
    xfopen(const char *path, const char *mode)
    {
            FILE *fp = path[0] != '-' || path[1] != '\0' ? 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;
    }