当fscanf返回1时,它始终返回0

时间:2016-08-11 03:33:06

标签: c matrix file-io scanf

我有一个函数,它接收文件流并将存储在该文件中的整数读入1D矩阵。我遇到的问题是我的fscanf始终返回0,而不是像我期望的那样返回1。我知道一个事实,我的文件的开头格式正确,并按预期,但我无法弄清楚为什么它不会读取第一行。我做错了什么?

/* FUNCTION: readToMatrix
    DESCRIPTION:
        This takes an input stream and reads the file (as described in the header documentation),
        filling the array with the integers contained in the input file stream.
    INPUTS:
        file stream, int *array, matrix width
    OUTPUTS:
        Writes to array
    RETURN:
        Returns 0 on success, nonzero on an unexpected failure.
*/

int readToMatrix( FILE *input, int *array, size_t matWidth )
{
    int x,y;
    long num;

    for ( y = 0; y < matWidth; ++y)
    {
        for ( x = 0; x < matWidth-1; ++x )
        {
            // if fscanf doesn't read 1 number or if EOF then return
            if ( fscanf(input, "%ld,", &num) != 1 || feof(input) ) return -1;
            array[x + y*matWidth] = num;
        }
        if ( fscanf(input, "%ld ", &num) != 1 || feof(input) ) return -1;
        array[x + y*matWidth] = num;
    }   
    return 0;
}

注意:这是输入文件开头的简短片段。

12177,12690,12499,12985,13005,12574,12882,12896,13026,14539,13704,13539,15182,14361,14539,15333,14615,15231,

2 个答案:

答案 0 :(得分:1)

循环中存在一些小问题。 修复这些,然后它可以正确运行:

#include<stdio.h>
int readToMatrix( FILE *input, int *array, size_t matWidth , size_t matHeight)
{
    int x,y;
    long num;
    for ( y = 0; y < matHeight; y++)
    {
        for ( x = 0; x < matWidth; x++ )
        {
            // if fscanf doesn't read 1 number or if EOF then return
            if ( fscanf(input, "%ld,", &num) != 1 || feof(input) ) return -1;    
            array[x + y*matWidth] = num;
        }    
    }       
    return 0;
}
int main()
{
    FILE *fd;
    int matWidth = 5 ;
    int matHeight = 5;
    int array[18]; 
    int i;
    fd=fopen("matrix.txt","r");
    if(fd == NULL)
    {
        printf("open failed!\n");
    }
    else
    {
        readToMatrix( fd, array, matWidth , matHeight);
        fclose(fd);
    }
    for(i=0;i<18;i++)
    {
        printf("%d:%d\n",i,array[i]);
    }
    return 0;
}

这是matrix.txt:

12177,12690,12499,12985,13005,12574,12882,12896,13026,14539,13704,13539,15182,14361,14539,15333,14615,15231 

输出: 0:12177 1:12690 2:12499 3:12985 4:13005 5:12574 6:12882 7:12896 8:13026 9:14539 10:13704 11:13539 12:15182 13:14361 14:14539 15:15333 16:14615 17:15231

答案 1 :(得分:0)

我发现了问题。出于某种原因,将文件流传递给函数是行不通的。当我创建函数创建文件流并在函数本身中打开文件时(可能应该如此),一切都运行良好。