1、使用VS新建空工程,直接点击确定,如下所示。
2、新建c文件,用于C语言编译器,输入main.c文件,如下所示。
3、参考代码:
#include <stdio.h>
int main()
{
//下面是写数据,将数字0~9写入到data.txt文件中
FILE *fpWrite=fopen("data.txt","w")
if(fpWrite==NULL)
{
return 0
}
for(int i=0i<10i++)
fprintf(fpWrite,"%d ",i)
fclose(fpWrite)
//下面是读数据,将读到的数据存到数组a[10]中,并且打印到控制台上
int a[10]={0}
FILE *fpRead=fopen("data.txt","r")
if(fpRead==NULL)
{
return 0
}
for(int i=0i<10i++)
{
fscanf(fpRead,"%d ",&a[i])
printf("%d ",a[i])
}
getchar()//等待
return 1
}
4、编译完成后,运行exe程序,执行后显示console程序。
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 )
}