现在的位置: 首页 > 综合 > 正文

从文件读入整数并动态设置数组内容

2019年08月06日 ⁄ 综合 ⁄ 共 966字 ⁄ 字号 评论关闭

#include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
int main(void)
{
    FILE * pfstream;
    int row = 0;
    int col = 0;
    int i = 0;
    int j = 0;
    int item;
    int *narray = NULL;
    if( (pfstream = fopen( "input.txt", "r" )) == NULL ){
        printf( "The file 'input.txt' can not be opened/n" );
        exit(-1);
    }
    else{

        fscanf(pfstream,"%d",&row);
        fscanf(pfstream,"%d",&col);

        if (row > 0 && col > 0)
        {
            narray = malloc(sizeof(int)*row*col);
            while (fscanf(pfstream,"%d",&item) != EOF)
            {
                narray[i++] = item;
                //if (i == row*col)

                //    break;

            }
        } 
        //printf( "The file 'input.txt' was opened/n" );

    }
    
    for(= 0; i < row; i++)
    {
        for (= 0; j < col; j++)
        {
            printf("%4d",narray[i*col + j]);        
        }
        printf("/n");
    }
    printf("/n");
    fclose(pfstream);
    free(narray);
    return 0;
    
}

抱歉!评论已关闭.