1. c語言如何讀取TXT中的中文字元串
#include<stdio.h>
intmain(void)
{
FILE*p;
charch;
p=fopen("a.txt","r");
while(!feof(p))
{
if(fgetc(p)=='>')
{
while((ch=fgetc(p))!='<')
{
putchar(ch);
}
printf(" ");
}
}
fclose(p);
return0;
}
//昨天我說了沒編譯估計會出錯,這次沒事了運行通過
//還有隻能讀英文,喬丹不行,這是因為c編譯器不支持unicode編碼,char類型的是只能表示128個字元,Unicode是兩個位元組,可以表示漢字。
2. c語言讀取txt文件內容
用C語言從txt文件中讀取數據,可以使用C標准庫文件自帶的文件介面函數進行操作。
一、打開文件:
FILE *fopen(const char *filename, const char *mode);
因為txt文件為文本文件, 所以打開時選擇的mode應為"r"或者"rt"。
二、讀取文件:
讀取文件應根據文件內容的格式,以及程序要求,選擇讀取文件的函數。可以使用一種,也可以幾種混用。 常用的文件讀取函數如下:
1、fgetc, 從文件中讀取一個位元組並返回。 適用於逐個位元組讀取。
2、 fgets, 從文件中讀取一行。適用於整行讀取。
3、fscanf, 格式化讀取文件, 在已經清楚文件存儲格式下,可以直接用fscanf把文件數據讀取到對應類型的變數中。
4、fread, 整塊讀取文件, 對於txt文件比較少用。
三、關閉文件:
讀取結束後,應調用fclose函數關閉文件。
3. C語言如何從txt文件中讀入漢字並將其存在字元串數組中...
程序代碼:
#include<stdio.h>
#include<stdlib.h>
#defineMAXSIZE1024
intmain(intargc,char*argv[])
{
FILE*fp;
charbuf[MAXSIZE];
fp=fopen("./hanzi.txt","r");
if(fp==NULL)
{
perror("calltofopen!");
exit(1);
}
fread(buf,1,MAXSIZE,fp);
printf("%s ",buf);
return0;
}
附hanzi.txt文件內容:
你好,很高興認識你!希望你的人生的每一天都會像今夜的星辰一樣,燦爛無比!
運行結果截圖:
4. 怎麼用c語言讀取txt中的中文信息
用fscanf(%s)或者fgets都可以讀,中文就是一個普通的字元串。
5. 用c語言從txt文件中讀取中文並顯示出來
很簡單的一個功能,現在寫的是將源文件寫死的
#include"stdafx.h"
intmain(void)
{
charfilename;
FILE*file=fopen("F:\wz-mac.txt","r");//打開文件
while((filename=fgetc(file))!=EOF)
{
printf("%c",filename);//列印內容到屏幕
}
return0;
}
6. C語言從txt中讀取漢字到數組
漢字在ANSI/GBK或UCS-2/UTF-16編碼中佔2個位元組,在UTF-8中佔3個位元組,在UCS-4/UTF-32中佔4個位元組。如果確定編碼(默認一般是ANSI/GBK)的話,就可以判斷出一個漢字的大小。由於fgetc只能處理單位元組數據,且char無法存放超過一個位元組,因此應該把漢字(無論是幾個)作為數組處理。具體可以用fread(s,n,1,fp);來從文件fp讀入指定的n位元組到字元串s中。也可以用fscanf配合%s使用。讀入一行的話,可以考慮fgets。
對於寬字元而言,可以用wchar_t代替char,用fgetwc代替fgetc。不過wchar_t和對應函數的行為是平台相關的,一般也不適合ANSI/GBK兼容窄字元串處理。
====
[原創回答團]
7. 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 );
}
(7)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] = '