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_File Io - Fatal编程技术网

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

C从一个文件中读取数据,并将计算结果存储在另一个文件中,c,file,file-io,C,File,File Io,我是C语言的初学者。在这里,我想从文件*fileptrIn中读取数据并进行一些计算,然后将答案存储在*fileptrOut中。但是我得到了一个无限循环,文件中的第一个元素是fileptrIn。它仅在终端中重复打印文件*fileptrIn中的第一个元素。因为我没有得到任何编译错误,所以我无法检测到错误。对编辑我的代码有什么建议吗 #include<stdio.h> int main(void) { int value; int total = 0; int count = 0; F

我是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;
}
#包括
内部主(空)
{
int值;
int-total=0;
整数计数=0;
文件*fileptrIn;
fileptrIn=fopen(“input.txt”,“r”);
if(fileptrIn==NULL)
{
printf(“\n打开读取时出错。\n”);
返回-1;
}
printf(“\n数据:\n”);
fscanf(fileptrIn、%d、&value);
而(!feof(fileptrIn))
{
printf(“%d”,值);
总+=价值;
++计数;
}
fclose(fileptrIn);
返回0;
}

您没有在循环中读取任何内容,因此文件指针不会前进到EOF(除其他答案外),并且从我的注释继续,您需要验证所有输入。您可以在删除
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个值,等等)。基本上它是
用于(int i=0;i
(或您想要的任何格式)您必须确保存储的数据不会超过阵列所能容纳的数据量。
:)
while (fscanf (fileptrIn, "%d", &value) == 1) {
    printf ("%d", value);
    total += value;
    ++count;
}