C语言可以使用fopen()函数读取txt文本里。
示例:
#include <stdio.h>
FILE *stream, *stream2
void main( void )
{
int numclosed
/* Open for read (will fail if file "data" does not exist) */
if( (stream = fopen( "data", "r" )) == NULL )
printf( "The file 'data' was not opened\n" )
else
printf( "The file 'data' was opened\n" )
/* Open for write */
if( (stream2 = fopen( "data2", "w+" )) == NULL )
printf( "The file 'data2' was not opened\n" )
else
printf( "The file 'data2' was opened\n" )
/* Close stream */
if(fclose( stream2 ))
printf( "The file 'data2' was not closed\n" )
/* All other files are closed: */
numclosed = _fcloseall( )
printf( "Number of files closed by _fcloseall: %u\n", numclosed )
}
扩展资料
使用fgetc函数
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
FILE *stream
char buffer[81]
int i, ch
/* Open file to read line from: */
if( (stream = fopen( "fgetc.c", "r" )) == NULL )
exit( 0 )
/* Read in first 80 characters and place them in "buffer": */
ch = fgetc( stream )
for( i=0(i <80 ) &&( feof( stream ) == 0 )i++ )
{
buffer[i] = (char)ch
ch = fgetc( stream )
}
/* Add null to end string */
buffer[i] = '\0'
printf( "%s\n", buffer )
fclose( stream )
}
一、编程思路。1 以文本方式打开文件。
3 判断fscanf的返回值,如果显示到达文件结尾,退出输入。
4 关闭文件。
5 使用数据。
二、代码实现。
设定文件名为in.txt, 存有一系列整型数据,以空格或换行分隔。
代码可以写作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
int main()
{
int v[100]//开一个足够大的数组。
int i = 0, j
FILE *fp//文件指针
fp = fopen("in.txt", "r")//以文本方式打开文件。
if(fp == NULL) //打开文件出错。
return -1
while(fscanf(fp, "%d", &v[i]) != EOF) //读取数据到数组,直到文件结尾(返回EOF)
i++
fclose(fp)//关闭文件
for(j = 0j <ij ++)//循环输出数组元素。
{
printf("%d ", v[j])
}
return 0
}
当文件内容为:
1 35 6 8 9 9
10 123 34
76 54 98
程序输出:
1 35 6 8 9 9 10 123 34 76 54 98
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)