【发布时间】:2011-01-07 23:14:45
【问题描述】:
各位程序员,
我想逐行读取由记事本创建的 Unicode (UTF-8) 文本文件,我不想在屏幕上显示 Unicode 字符串,我只想读取和比较字符串!。
此代码逐行读取ANSI文件,并比较字符串
我想要什么
逐行读取test_ansi.txt
如果 line = "b" 打印 "YES!"
否则打印“否!”
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 个多月后我没有找到任何好的 C 代码/库可以读取以 UTF-8 编码的文件!,我不知道确切原因,但我认为标准 C 不支持 Unicode!
读取 Unicode 二进制文件没问题!但问题是二进制文件大多数已经以二进制模式创建!这意味着如果我们要读取由记事本创建的 Unicode (UTF-8) 文件,我们需要将其从UTF-8 文件转 BINARY 文件!
此代码将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 如果 line = "ب" 打印 "YES!" 否则打印“否!”
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文件吗? (我不确定)
谢谢。
【问题讨论】: