文件读写相关。
1。我的目的是实现文件读写,编辑功能。我会在文件中间插入一些我想要加入的文本。我通过查找关键字来确定文件中的位置。并在该位置上插入我要插入的文本。
2。 最初我没有考虑支持UNICODE ,但在遇到带有汉字的目录时,fopen失败了。
3。 如今我加入unicode 处理 。我用_wfopen_s 以二进制方式打开文件。 之后依然用asrcII的api处理 这样有问题吗?
我用char数组存储的二进制数据。
=============================
FILE*fp;
_wfopen_s(&fp,strPath,L"rb");
if(!fp)
{
return ;
}
long len,len2;
fseek(fp,0,SEEK_END);
len = ftell(fp);
fseek(fp,0,SEEK_SET);
char* data;
char* file_buf = NULL;
if( len )
{
file_buf = new char[len+1];
if(file_buf)
{
file_buf[len] = L'\0';
fread(file_buf,1,len,fp);
data = file_buf;
}
fclose(fp);
}
else
{
// empty file
fclose(fp);
return;
}
if (NULL == data)
{
TRACE("data is NULL\n");
delete [] file_buf;
return;
}
=============================
通过查找关键字定位要编辑的位置。
char * pdata = strstr(data,pstrKeyword);
用3个指针标记文件
pUp 数组中 0 到 pdata 部分 长度len2
pIn 要插入的数据
pdata pdata 到数据结尾
================================
最后写数据
_wfopen_s(&fp,strPath,L"wb");
fwrite(pUp,1,len2,fp);
fprintf(fp,"%s\n",psTest);
fwrite(pdata,1,(len-len2),fp);
=======================================================================
4。 看看这么处理有什么问题。
5。 有什么更好的方法么?
[解决办法]
有问题。
wchar_t *fgetws( wchar_t *string, int n, FILE *stream );
int swscanf( const wchar_t *buffer, const wchar_t *format [, argument ] ... );
int swprintf( wchar_t *buffer, const wchar_t *format [, argument] ... );
wchar_t *wcsstr( const wchar_t *string, const wchar_t *strCharSet );
size_t wcslen( const wchar_t *string );
[解决办法]
有问题的啊。建议全部换成unicode处理吧。