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] = '