Which ffunction do I use?

This is a discussion on Which ffunction do I use? within the C Programming forums, part of the General Programming Boards category; Hello, I would like to read in a file of the form: 1 2 1 1 3 1 1 4 ...

  1. #1
    Not bad at Crack Attack!
    Join Date
    Aug 2003
    Posts
    45

    Which ffunction do I use?

    Hello,

    I would like to read in a file of the form:

    1 2 1
    1 3 1
    1 4 1
    ....
    2 1 1
    2 4 1
    ...

    etc

    and store the int in the right hand column in the two dimensional array at array[i][j] where i is obviously the first entry of a line and j the second.

    My approach presently is to use fgets and read in line by line, obtaining a char[] and then hop through it, doing atoi on the fields seperated by white space.

    Is this implementation plausible? I have found a panoply of functions beginning with f (hence ffunctions - a terrible joke I know) for working with files and get the feeling that there may be a slicker implementation.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Files are generally well formatted, you should be able to use fscanf without any "issues" here:
    Code:
    char  array[M][N]; /* M and N are macros for the size */
    FILE *fp;
    int   i, j;
    int   x;
    
    /* Open fp with fopen here */
    /* Check for success */
    if (!fp) {
      perror("File open failure");
    }
    else {
      while (fscanf(fp, "%d%d%d", &i, &j, &x) == 3) {
        /* Verify indices */
        if (i < 0 || i >= M || j < 0 || j >= N) {
          fprintf(stderr, "Index out of range\n");
          continue;
        }
        array[i][j] = x;
      }
      /* Check to see why we stopped */
      if (!feof(fp)) {
        if (ferror(fp) {
          fprintf(stderr, "Input error\n");
        }
        else {
          fprintf(stderr, "Invalid input\n");
        }
      }
    }
    My best code is written with the delete key.

  3. #3
    Not bad at Crack Attack!
    Join Date
    Aug 2003
    Posts
    45
    Thankyou Prelude.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21