
1、用fgets函数可以读取文件中某行的数据,某列数据就必须一个一个读入每行的第几个字符,再存入到一个字符串当中。
2、例程:
#include<stringh>
void main()
{
char a[100],b[100],c[100];
int i=3,j=4,k=0; //第三行,第四列
FILE fp = fopen("datatxt","r");
while(fgets(c,100,fp)){ //读入每行数据
i--;
if(i==0) strcpy(a,c); //读到第三行数据
b[k++]=c[j-1]; //把每行的那列字符拷到b中
}
b[k]=0;
printf("第%d行数据:%s\n",i,a);
printf("第%d列数据:%s\n",j,b);
fclose(fp);
}
C语言可以使用fopen()函数读取txt文本里。
示例:
#include <stdioh>
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 <stdioh>
#include <stdlibh>
void main( void )
{
FILE stream;
char buffer[81];
int i, ch;
/ Open file to read line from: /
if( (stream = fopen( "fgetcc", "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函数打开文本,例如filefp=fopen("intxt","r");//返回一个file类型的句柄
2然后就可以通过fcanf()函数对txt文本进行读取
3 *** 作完文本之后用fclose()函数
关闭已经打开的文件。
#include
int main()
{
int data;
file fp=fopen("intxt","r");
if(!fp)
{
printf("can't open file\n");
return -1;
}
while(!feof(fp))
{
fscanf(fp,"%d",&data);
printf("%4d",data);
}
printf("\n");
fclose(fp);
return 0;
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)