A. c語言fgets如何循環讀取整個文本文件的內容
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//函數返回fname指定文件的全部內容,如果打不開文件,則返回NULL,並顯示打開文件錯誤
char *getfileall(char *fname){
FILE *fp;
char *str;
char txt[1000];
int filesize;
if ((fp=fopen(fname,"r"))==NULL){
printf("打開文件%s錯誤\n",fname);
return NULL;
}
fseek(fp,0,SEEK_END);
filesize = ftell(fp);
str=(char *)malloc(filesize);
str[0]=0;
rewind(fp);
while((fgets(txt,1000,fp))!=NULL){
strcat(str,txt);
}
fclose(fp);
return str;
}
int main(){
char *p;
char *fname="D:\\temp.txt";
p=getfileall(fname);
if (p!=NULL) puts(p);
}
B. 用c語言讀取一個txt文件
如果預知前面的是英文後面的是中文,即可分開:
#include<stdio.h>
#define N 100
void main() { FILE *fp; char s[256],y[N][20],h[N][20]; int i,n;
if ( fp=fopen("c:\data\text.txt","r") ) {
n=0;
while ( !feof(fp) ) {
fgets(s,256,fp); sscanf("%s%s",y[n],h[n]); n++; if ( n>=N ) break;
}
fclose(fp);
printf("英文: "); for ( i=0;i<n;i++ ) printf("%s ",y[i]); printf(" ");
printf("中文: "); for ( i=0;i<n;i++ ) printf("%s ",h[i]); printf(" ");
} else printf("無法打開文件讀取。 ");
}
如果中英文順序不一定,且不會有中英文混合單詞:
#include<stdio.h>
#include<string.h>
#define N 100
void main() { FILE *fp; char s[256],y[N][20],h[N][20]; int i,n;
if ( fp=fopen("c:\data\text.txt","r") ) {
n=0;
while ( !feof(fp) ) {
fgets(s,256,fp); sscanf("%s%s",y[n],h[n]);
if ( y[n][0]<0 ) { strcpy(s,y[n]);strcpy(y[n],h[n]);strcpy(h[n],s); } //漢字字元ASCII碼小於0
n++; if ( n>=N ) break;
}
fclose(fp);
printf("英文: "); for ( i=0;i<n;i++ ) printf("%s ",y[i]); printf(" ");
printf("中文: "); for ( i=0;i<n;i++ ) printf("%s ",h[i]); printf(" ");
} else printf("無法打開文件讀取。 ");
}
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語言循環讀取txt文件數據擴展閱讀
使用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] = '