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
程序代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
// C++读取文本到数组.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
int readfile1D()
{
char a[100];
int i;
FILE *fp = fopen ( "1.txt" , "r" );
if (fp == NULL)
{
printf ( "文件读取无效.\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 ( "文件无效" );
return -1;
}
for (i=0; i<3; i++)
{
for (j=0; j<5; j++)
{
fscanf (fp, "%d" ,&a[i][j]);
}
//fscanf(fp,"\n"); 不要也罢
}
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;
}
|
以上就是小编为大家带来的c语言实现把文件中数据读取并存到数组中全部内容了,希望大家多多支持服务器之家~