如何将指针与 getc 结合使用?
我有一个函数 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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
原因是每次执行 getNum 时都会重新打开该文件。当您打开文件进行读取时,它将从文件的开头开始。相反,只需打开一次。
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.每次调用 getNum 时都会重新打开该文件,因此您自然会回到开始处。
相反,在主程序中打开文件并将 FILE * 传递给 getNum()。
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().
每次调用函数时都会重新打开文件。新打开的文件从头开始扫描。
另一种方法是在 getNum() 之外打开文件一次。您可以将 FILE* 作为参数传递给 getNum()。
另外,您没有关闭该文件。在所有调用 getNum() 后,使用 fclose() 关闭文件。
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().
像这样的东西:
Something like: