一、打开文件:
FILE *fopen(const char *filename, const char *mode)
因为txt文件为文本文件, 所以打开时选择的mode应为"r"或者"rt"。
二、读取文件:
读取文件应根据文件内容的格式,以及程序要求,选择读取文件的函数。可以使用一种,也可以几种混用。 常用的文件读取函数如下:
1、fgetc, 从文件中读取一个字节并返回。 适用于逐个字节读取。
2、 fgets, 从文件中读取一行。适用于整行读取。
3、fscanf, 格式化读取文件, 在已经清楚文件存储格式下,可以直接用fscanf把文件数据读取到对应类型的变量中。
4、fread, 整块读取文件, 对于txt文件比较少用。
三、关闭文件:
读取结束后,应调用fclose函数关闭文件。
//data.txt文件内容如下\x0d\x0a\x0d\x0a1个猪\x0d\x0a2个猪\x0d\x0a3个猪\x0d\x0a4个猪\x0d\x0a5个猪\x0d\x0a6个猪\x0d\x0a7个猪\x0d\x0a8个猪\x0d\x0a\x0d\x0a//运行结果一\x0d\x0athe 8 line :8 个 猪\x0d\x0a\x0d\x0aPress any key to continue \x0d\x0a//运行结果二\x0d\x0aout of range!\x0d\x0aPress any key to continue \x0d\x0a\x0d\x0a//代码如下\x0d\x0a#include \x0d\x0a#include \x0d\x0a#include \x0d\x0amain(void)\x0d\x0a{\x0d\x0aint lid,cnt=0,flag=0\x0d\x0achar buf[100]="\0"\x0d\x0aFILE *fp\x0d\x0a\x0d\x0asrand((unsigned)time(NULL))\x0d\x0afp=fopen("data.txt","r")\x0d\x0alid= rand()%10+1\x0d\x0awhile (fgets(buf,99,fp)!=NULL)\x0d\x0a{\x0d\x0aif(cnt==lid)\x0d\x0a{\x0d\x0aprintf("the %d line :%s\n",lid+1,buf)\x0d\x0aflag=1\x0d\x0abreak\x0d\x0a}\x0d\x0acnt++\x0d\x0a}\x0d\x0aif (flag==0)\x0d\x0a{\x0d\x0aprintf("out of range!\n")\x0d\x0a}\x0d\x0a}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 )
}