【问题标题】:C read data from one file and store calculations in another fileC 从一个文件中读取数据并将计算结果存储在另一个文件中
【发布时间】:2017-05-30 04:19:19
【问题描述】:

我是 C 语言的初学者。在这里,我想从文件*fileptrIn 中读取数据并进行一些计算,并将答案存储在*fileptrOut 中。但是我得到了一个无限循环,文件中的第一个元素是 *fileptrIn。它仅在终端中重复打印文件 *fileptrIn 中的第一个元素。由于我没有收到任何编译错误,因此无法检测到错误。有什么建议可以编辑我的代码吗?

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

【问题讨论】:

标签: c file file-io


【解决方案1】:

除了其他答案,继续我的评论,您需要验证所有输入。您可以在消除while (!feof(file)) 问题的同时完成此操作,如下所示:

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

【讨论】:

  • Thx 它也有效:) 除此之外,我可以做哪些更改来将多条记录写入我的新文件 *fileptrOut? :(@david-c-rankin
  • 您正在从文件中读取int 值,因此通常您会将读取的值存储在数组中。 (在代码开头初始化int n = 0; int arrray[500] = {0};,然后在每次读取value 时,它是array[n++] = value; 然后您可以将数组写入您的fileptrOut。您必须选择您希望写入的格式(例如1 - 每行值,每行 10 个值,等等...)基本上它是 for (int i = 0; i &lt; n; i++) fprintf (fileptrOout, "%d\n", array[i]);(或您想要的任何格式)您必须确保您存储的数量不超过数组可以容纳的数量 :)
【解决方案2】:
while(!feof(fileptrIn))
{
    printf("%d", value);

    total += value;

    ++count;
}

您没有在循环内读取任何内容,因此文件指针不会前进到 EOF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多