tags:

views:

48

answers:

4

I have a function getNum(), which gets a number from file and returns it. When I go back into getNum() I have lost the pointer and it starts at the begging of the file again. I'm wondering How do I get the location of where getc is and then go back to that place. I couldn't find how to do this in the manual or in forums. Thank you.

#include <stdio.h>
#include <stdlib.h>

int getNum();
int getLine();
int getMatrix();



main() {
int num;
int two;
num = getNum();
printf("%d\n", num);
two = getNum();
printf("%d\n", two);

}

int getNum() {
  FILE *infile;
    infile = fopen("matrix.txt","r");
  int c;
  double value = 0;

  while ((c=getc(infile)) != '\n') {
    if(c==32){
      if(value != 0){
        return(value);
      }
      //otherwise keep getting characters
    }
    else if ((c<=47)||(c>=58)){
      printf("incorrect number input %d\n", c);
      exit(1);
    }
    else {
      value = (10*value) + c - '0';
    }
  }
  return(value);
}
+3  A: 

The reason is that you reopen the file each time you execute getNum. When you open a file for reading, it starts at the start of the file. Instead open it just once.

int main(int argc, char *argv[])
{
  ...
  FILE *infile;
  ...
  infile = fopen("matrix.txt","r");
  ...
  getNum(infile)
  ...
  fclose(infile);
  return 0;
}


int getNum(File *infile)
{
  // Same as before, just no file opening.
}
torak
+2  A: 

You re-open the File each time you Call getNum, so naturally you are back at the start.

Instead open the file in your main and pass the FILE * to getNum().

djna
+1  A: 

You're opening the file anew with each function call. The newly opened file begins scanning from the beginning.

An alternative would be to open the file once, outside getNum(). You could pass the FILE* to getNum() as an argument.

Also, you're not closing the file. Use fclose() to close the file after all the calls to getNum().

Andy Thomas-Cramer
+1  A: 

Something like:

int getNum( FILE* fp );
...

int n;
FILE* file = fopen( "file.txt" );
assert( file );
do {
    n = getNum( file );
    /* ... */
}
while ( n != -1 ); /* or something */
fclose( file );
Nikolai N Fetissov