C语言如何读取txt文本里面的内容?

Python017

C语言如何读取txt文本里面的内容?,第1张

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 以fopen打开文件,使用"r"方式。

2 通过fscanf,按照文件中的数据格式,读入数据。

3 关闭文件并使用数据。

如文件in.txt中存在三个以空格分隔的数据,依次为整型,字符串,以及浮点型,则读取数据的代码可以写作:

int main()

{

    FILE *fp

    int a

    char s[100]

    float f

    fp = fopen("in.txt", "r")

    if(fp == NULL) return -1//打开文件失败,结束程序。

    fscanf(fp,"%d%s%f",&a,s,&f)

    fclose(fp)

    

    printf("read value: %d, %s, %f", a,s,f)

}

#include <stdio.h>

int main()

{

FILE *fp=NULL

int a[160]

int i=0

fp=fopen("data.txt","r")

if ( !fp )

{

printf("open file error\n")

return -1

}

while( !feof(fp) )

{

if ( fscanf( fp , "%d" ,&a[i] ) !=1 )

break

i++

fgetc(fp) //过滤掉分隔符

}

fclose(fp)

//以下倒序输出数据

printf("i=%d\n" , i )

while( --i >= 0 )

{

printf("%d," , a[i] )

if ( i %10 == 0 )

printf("\n")

}

return 0

}