简体   繁体   English

C从一个文件读取数据并将计算结果存储在另一个文件中

[英]C read data from one file and store calculations in another file

I'm a beginner to C language. 我是C语言的初学者。 Here I want to read data from file *fileptrIn and do some calculations, and store the answers in *fileptrOut. 在这里,我想从文件* fileptrIn中读取数据并进行一些计算,并将答案存储在* fileptrOut中。 But I get a infinite loop with the first element in the file *fileptrIn. 但是我在文件* fileptrIn中的第一个元素上遇到了无限循环。 It prints only the first element in the file *fileptrIn repeatedly in the terminal. 在终端中,它仅重复打印文件* fileptrIn中的第一个元素。 As I don't get any compilation errors, I'm unable to detect the error. 由于没有任何编译错误,因此无法检测到该错误。 Any suggestions to edit my code? 有任何编辑我的代码的建议吗?

#include<stdio.h>

int main(void)
{
int value;
int total = 0;
int count = 0;

FILE *fileptrIn;

fileptrIn = fopen("input.txt", "r");

if(fileptrIn == NULL)
{
    printf("\nError opening for reading.\n");

    return -1;
}

printf("\nThe data:\n");

fscanf(fileptrIn, "%d", &value);

while(!feof(fileptrIn))
{
    printf("%d", value);

    total += value;

    ++count;
}

fclose(fileptrIn);

return 0;
}
while(!feof(fileptrIn))
{
    printf("%d", value);

    total += value;

    ++count;
}

You are not reading anything inside loop so the file pointer dont advance to reach EOF 您没有在循环内读取任何内容,因此文件指针不会前进到EOF

In addition to the other answer, and continuing from my comment, you need to validate all input. 除了其他答案,并继续我的评论,您需要验证所有输入。 You can accomplish this while removing the while (!feof(file)) problem as follows: 您可以在消除while (!feof(file))问题的while (!feof(file))完成此操作,如下所示:

while (fscanf (fileptrIn, "%d", &value) == 1) {
    printf ("%d", value);
    total += value;
    ++count;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM