#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    13
    Rep Power
    0

    Get a char from a specific location


    Hello I started with C this week to work on a case study. I have been looking all over for the past few hour to find a function that gets a specific character from a file, rather than just following the stream. I'm a high school student and kinda a noob at c.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    San Francisco Bay
    Posts
    1,939
    Rep Power
    1313
    Try the fseek function (stdio.h):
    c Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int main(int argc, char **argv) {
        FILE *fp;
        int k;
        int c;
        char *endptr;
     
        if (argc < 3) {
            fprintf(stderr, "Error: usage: %s {filename} {k}\n", argv[0]);
            fprintf(stderr, "Error: too few arguments\n");
            return 2;
        }
     
        k = strtol(argv[2], &endptr, 10);
        if (*endptr) {
            fprintf(stderr, "Error: expected integer\n");
            return 2;
        }
     
        if (!(fp = fopen(argv[1], "r"))) {
            fprintf(stderr, "Error: couldn't open %s\n", argv[1]);
            return 1;
        }
     
        if (fseek(fp, k, SEEK_SET) < 0) {
            fprintf(stderr, "Error: couldn't seek to position %d\n", k);
            return 1;
        }
     
        c = fgetc(fp);
     
        if (c == EOF) {
            fprintf(stderr, "Error: EOF\n");
            return 1;
        }
     
        printf("%c[0x%02x]\n", c, c);
     
        return 0;
    }
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    71
    Rep Power
    3
    I'll ask before someone else does. How do you specify that specific character? Is it postion in the file? Is it character value?
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    13
    Rep Power
    0
    Thank you Lux that was just the thing I needed. And G4 it was the location not the value of the character it's self. Thank you for your help!

IMN logo majestic logo threadwatch logo seochat tools logo