c language implementation of the file data read into an array
- 2020-05-10 18:34:01
- OfStack
1.txt
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
2.txt
1 2 3 4 5
2 3 4 5 6
4 5 6 7 8
Program code:
// C++ Read the text into the array .cpp : Define the entry point for the console application.
//
#include "stdafx.h"
int readfile1D()
{
char a[100];
int i;
FILE *fp = fopen("1.txt","r");
if(fp == NULL)
{
printf(" Invalid file read .\n");
return -1;
}
for(i = 0; !feof(fp); i++)
fscanf(fp, "%d", &a[i]);
fclose(fp);
for(i=0; i < 20; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
int readfile2D()
{
int a[3][5];
int i,j;
FILE* fp = fopen("2.txt","r");
if(fp == NULL)
{
printf(" The file is invalid ");
return -1;
}
for(i=0; i<3; i++)
{
for(j=0; j<5; j++)
{
fscanf(fp,"%d",&a[i][j]);
}
//fscanf(fp,"\n"); Don't let it be
}
fclose(fp);
for(i=0; i<3; i++)
{
for(j=0; j<5; j++)
printf("%d ", a[i][j]);
printf("\n");
}
printf("\n");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
readfile1D();
readfile2D();
return 0;
}