Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何停止读取文件?_C_File - Fatal编程技术网

C 如何停止读取文件?

C 如何停止读取文件?,c,file,C,File,当我的文件结束时,如何使它停止? txt文件是这样的 2 4 5.6 7 8 但它会打印出来 2 x 4 y 5 x 6 y 7 x 8 y 1429697293 x 4199392 y int x[20]; int y[20]; FILE *fp; fp = fopen("coord.txt", "r"); for(int i = 0; i<4; i++){ if((x[i]=='\0')||(y[i]=='\0')) break;

当我的文件结束时,如何使它停止? txt文件是这样的

2 4

5.6

7 8

但它会打印出来

2 x 4 y

5 x 6 y

7 x 8 y

1429697293 x 4199392 y

int x[20];
int y[20];
FILE *fp;
fp = fopen("coord.txt", "r");


for(int i = 0; i<4; i++){
    if((x[i]=='\0')||(y[i]=='\0')) break;
    fscanf(fp, "%d %d", &x[i],&y[i]);

}

for(int i=0; i<4;i++)
    {
        if((x[i]=='\0')||(y[i]=='\0')) break;
        printf("%d x  , %d y \n",x[i],y[i]);
    }
intx[20];
int y[20];
文件*fp;
fp=fopen(“coord.txt”,“r”);
对于(inti=0;i好的,我刚刚写了

   while (fscanf(fp, "%d %d", &x[i],&y[i]) != EOF)
   printf("%d x  , %d y \n",x[i],y[i]);

而不是一切,它工作。

while(i<20&&fscanf(fp,%d%d“,&x[i],&y[i])==2)){…}
注意@WeatherVane注释中
while()
循环中的附加条件,您必须保护数组边界并验证
fscanf()
返回。您必须根据指定的转换次数验证
fscanf()
返回,而不是
EOF
非常感谢David和@WeatherVane