2

我有一个函数 getNum(),它从文件中获取一个数字并返回它。当我回到 getNum() 时,我丢失了指针,它再次开始请求文件。我想知道如何获得 getc 所在的位置,然后回到那个地方。我在手册或论坛中找不到如何执行此操作。谢谢你。

#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);
}
4

4 回答 4

3

原因是每次执行时都会重新打开文件getNum。当您打开一个文件进行读取时,它从文件的开头开始。而是只打开一次。

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.
}
于 2010-09-29T17:46:38.970 回答
2

每次调用 getNum 时都会重新打开文件,所以很自然地又回到了起点。

而是在 main 中打开文件并将 FILE * 传递给 getNum()。

于 2010-09-29T17:46:52.063 回答
1

您正在使用每个函数调用重新打开文件。新打开的文件从头开始扫描。

另一种方法是在 getNum() 之外打开文件一次。您可以将 FILE* 作为参数传递给 getNum()。

此外,您没有关闭文件。在所有对 getNum() 的调用之后,使用 fclose() 关闭文件。

于 2010-09-29T17:47:05.613 回答
1

就像是:

int getNum( FILE* fp );
...

int n;
FILE* file = fopen( "file.txt" );
assert( file );
do {
    n = getNum( file );
    /* ... */
}
while ( n != -1 ); /* or something */
fclose( file );
于 2010-09-29T17:47:44.037 回答