A. 关于c语言中文本文件的逐行读取的实现
#include
<stdio.h>
int
ReadData(void)
{
unsigned
int
rc,
i,
get;
/*get为读取一个字节*/
FILE
*fp;
fp
=
fopen("helloworld.txt",
"r+");
if
(fp
==
NULL)
{
return
-1;
/*打开文件失败返回-1*/
}
rc=0;
i=0;
while
((get
=
fgetc(fp))
!=
EOF)
{
if((char)get
==
'\n')
/*记录换行符*/
{
rc
=
ftell(fp);
i++;
}
rc++;
}
return
i;
}
int
main()
{
int
row;
row
=
ReadData();
printf("Row
=
%d\n",
row);
/*打印文件行数*/
return
0;
}
B. 从文本文件里读取数字,c语言如何实现
voidmain()
{
FILE*fin;
inta,b,c,d;
chars[20];
floatf1,f2,f3,f4;
fin=fopen("abc.txt","r");//打开
fscanf(fin,"%1d%1d%1d%1d",&a,&b,&c,&d);//按1位整型读前4个数
printf("a=%db=%dc=%dd=%d ",a,b,c,d);
rewind(fin);//文件回绕到开始处
fscanf(fin,"%s",s);//按字符串读一串
printf("s=%s ",s);
rewind(fin);//文件回绕到开始处
fscanf(fin,"%1f%1f%1f%1f",&f1,&f2,&f3,&f4);//按1位float型读前4个数
printf("%f%f%f%f ",f1,f2,f3,f4);
flcose(fin);
}
abc.txt内容:
123456789
读到数组:
inty[20];
inti;
fin=fopen("abc.txt","r");
for(i=0;i<9;i++)fscanf(fin,"%1d",&y[i]);
(2)c语言文本文件的读取扩展阅读
C语言中文件的读取
fopen(打开文件)
相关函数open,fclose
表头文件#include<stdio.h>
定义函数FILE*fopen(constchar*path,constchar*mode);
函数说明参数路径包含包含打开的文件路径和文件名,参数模式字符串则代表着流形态。
模式有以下几种形态类别:
r:预期文件,该文件必须存在。
r+:可读写的文件,该文件必须存在。
w:只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+:可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a以附加的方式打开只写文件。若文件不存在,则建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。
C. C语言如何读取txt文本里面的内容
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 " );
else
printf( "The file 'data' was opened " );
/* Open for write */
if( (stream2 = fopen( "data2", "w+" )) == NULL )
printf( "The file 'data2' was not opened " );
else
printf( "The file 'data2' was opened " );
/* Close stream */
if(fclose( stream2 ))
printf( "The file 'data2' was not closed " );
/* All other files are closed: */
numclosed = _fcloseall( );
printf( "Number of files closed by _fcloseall: %u ", numclosed );
}
(3)c语言文本文件的读取扩展阅读
使用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] = '