c语言如何读入文件
1. 如何用c语言从txt文件中读取数据
//其中的in.txt就是你要读取数据的文件,当然把它和程序放在同一目录
-------------------------------------
#include
<stdio.h>
int
main()
{
int
data;
file
*fp=fopen("in.txt","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;
}
2. c语言如何读取文件中的特殊数据。
我的方法是采用fgetc()函数逐个读取,遇到空格字符就将之前的内容保存到数组里面,遇到换行符就参数归零,在第二行重新读取文件内容。比如说第一个空格之前的是配置项vertex
第二个空格之前的是配置内容1,第三个空格之前的是配置内容2,读取完毕按照规则打印出来就行了,代码我懒得写了,希望你多多了解基本C库函数,锻炼自己的思路,C语言重要的是编程思想。
无论一个数据怎么长,怎么复杂,你都可以把他看成是一个个字符组成的,或者当成一个字符串。
3. 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] = '