简体   繁体   English

在eof之后从文件输入到C中的数组

[英]Inputting from a file to an array in C, after eof

I'm trying to put all of the information in a file into an array, after I have already looped through the file to see how many lines the file is. 在遍历文件以查看文件多少行之后,我试图将文件中的所有信息放入数组中。 If I putc a line of the file it seems to work, however, if I set the array locations to the file lines as I go back through the file and then print the array, the numbers come out way different from what they should be. 如果我在文件的一行上放了一点,那似乎就可以了,但是,如果我在遍历文件然后打印该阵列时将数组的位置设置为文件行,则数字的输出应与应有的数字不同。

Here's my code. 这是我的代码。

int main()
{

                            //Opens File

    char fName[20];

   // fName = getchar();

    scanf( "%s", fName);

    FILE *fpIn;

    fpIn = fopen ( fName, "rt");
   // fpIn = fopen( "test1.txt", "rt");

    if ( fpIn == NULL)
    {
        printf( "Unable to open: ");
        exit(99);
    }

                            //Gets Lines

    int lines=0;
    char ch;

    while((ch=fgetc(fpIn))!=EOF)
    {
        if (ch=='\n') { lines++; }

    }

    clearerr(fName *fpIn);
    fclose(fpIn);
    fopen(fName, "rt");

                            //Makes Array

    int *pA;

    pA = (int *)malloc(lines*sizeof(int));

                            //Fills Array

    for (int i=0; i<lines; i++)
    {
        while ((ch=fgetc(fpIn))!='\n')
        {
            pA[i] = ch;
        }
        ch=fgetc(fpIn);
    }

    for (int i=0; i<lines; i++)
    {
        printf("%d\n", pA[i]);
    }



    return 0;
}

Consider this part of the code: 考虑代码的这一部分:

    while ((ch=fgetc(fpIn))!='\n')
    {
        pA[i] = ch;
    }

i doesn't change during this loop, so pA[i] keeps being overwritten with each new character. 在此循环中i没有改变,因此pA[i]会不断被每个新字符覆盖。 You'll end up with pA[i] containing the last character on the line. 您将得到包含行中最后一个字符的pA[i]

While switching to the fscanf() statement instead of the getc() as suggested by Vaughn Cato was definitely helpful in getting me towards the right solution. 在切换到fscanf()语句而不是Vaughn Cato建议的getc()时,绝对可以帮助我找到正确的解决方案。 What made the real difference was removing the while statement that checked to make sure I had reached the end of the line before moving on to the next integer. 真正的不同之处在于,删除了while语句,该语句检查以确保在移至下一个整数之前已到达行尾。

The code now reads, 现在,代码显示为

for (int i=0; i<lines; i++)
    {
        fscanf(fpIn, "%lf", &pA[i]);
    }

And, so far, appears to work for all the appropriate data input files. 到目前为止,它似乎适用于所有适当的数据输入文件。

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

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