各位程序员,
我想按行读取由记事本创建的Unicode(UTF-8)文本文件,我不想在屏幕上显示Unicode字符串,我只想读取和比较字符串。
以下代码按行读取ANSI文件,并比较字符串
我的需求
按行读取 test_ansi.txt 文件
如果该行 =“b”,则输出“YES!”
否则输出“NO!”
read_ansi_line_by_line.c
#include <stdio.h>
int main()
{
char *inname = "test_ansi.txt";
FILE *infile;
char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */
char line_number;
infile = fopen(inname, "r");
if (!infile) {
printf("\nfile '%s' not found\n", inname);
return 0;
}
printf("\n%s\n\n", inname);
line_number = 0;
while (fgets(line_buffer, sizeof(line_buffer), infile)) {
++line_number;
/* note that the newline is in the buffer */
if (strcmp("b\n", line_buffer) == 0 ){
printf("%d: YES!\n", line_number);
}else{
printf("%d: NO!\n", line_number,line_buffer);
}
}
printf("\n\nTotal: %d\n", line_number);
return 0;
}
test_ansi.txt
a
b
c
编译
gcc -o read_ansi_line_by_line read_ansi_line_by_line.c
输出
test_ansi.txt
1: NO!
2: YES!
3: NO!
Total: 3
现在我需要读取由记事本创建的Unicode(UTF-8)文件,但是经过超过6个月的搜索,我没有找到任何能够读取UTF-8编码文件的好的C代码/库!我不知道确切的原因,但我认为标准C不支持Unicode!
读取Unicode二进制文件没问题!但问题在于二进制文件必须已经以二进制模式创建!这意味着,如果我们要读取由记事本创建的Unicode(UTF-8)文件,我们需要将其从UTF-8文件转换为二进制文件!
此代码将Unicode字符串写入二进制文件,注意C文件以UTF-8编码,并由GCC编译。
我想要的
将Unicode字符“ب”写入test_bin.dat
create_bin.c
#define UNICODE
#ifdef UNICODE
#define _UNICODE
#else
#define _MBCS
#endif
#include <stdio.h>
#include <wchar.h>
int main()
{
/*Data to be stored in file*/
wchar_t line_buffer[BUFSIZ]=L"ب";
/*Opening file for writing in binary mode*/
FILE *infile=fopen("test_bin.dat","wb");
/*Writing data to file*/
fwrite(line_buffer, 1, 13, infile);
/*Closing File*/
fclose(infile);
return 0;
}
编译
gcc -o create_bin create_bin.c
输出
create test_bin.dat
现在我想逐行读取二进制文件并进行比较!
我的需求
逐行读取test_bin.dat文件 如果行等于"ب"则打印"YES!" 否则打印"NO!"
read_bin_line_by_line.c
#define UNICODE
#ifdef UNICODE
#define _UNICODE
#else
#define _MBCS
#endif
#include <stdio.h>
#include <wchar.h>
int main()
{
wchar_t *inname = L"test_bin.dat";
FILE *infile;
wchar_t line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */
infile = _wfopen(inname,L"rb");
if (!infile) {
wprintf(L"\nfile '%s' not found\n", inname);
return 0;
}
wprintf(L"\n%s\n\n", inname);
/*Reading data from file into temporary buffer*/
while (fread(line_buffer,1,13,infile)) {
/* note that the newline is in the buffer */
if ( wcscmp ( L"ب" , line_buffer ) == 0 ){
wprintf(L"YES!\n");
}else{
wprintf(L"NO!\n", line_buffer);
}
}
/*Closing File*/
fclose(infile);
return 0;
}
输出
test_bin.dat
YES!
问题
这个方法太长了!而且不够强大(我是软件工程的初学者)
请问有谁知道如何读取Unicode文件?(我知道这不容易!) 请问有谁知道如何将Unicode文件转换为二进制文件?(简单方法) 请问有谁知道如何以二进制模式读取Unicode文件?(我不确定)
谢谢。