读写文件时的异常检查有关问题
读写文件时的错误检查问题
我用C语言或C++读取文件时,是否需要每一次读写都要检查正确性呢,如果读很多次,岂不是要增加许多代码。大家有没有什么好的建议。
下面是我的一段代码,显示非常繁琐:
hFile = fopen(pFileName, "rb ");
if(NULL == hFile)
{
printf( "Open file fail!\n ");
return FAIL;
}
size = fgetsize(hFile);
if(size < 0)
{
printf( "get file size fail!\n ");
fclose(hFile);
return FAIL;
}
if(0 == size)
{
printf( "void file\n ");
fclose(hFile);
return SUCCESS;
}
/*for other ebook*/
if(bufSize > 0)
size = bufSize;
if(size > TEXTBUF_MAXSIZE)
{
printf( "too large file!\n ");
size = TEXTBUF_MAXSIZE-1;
}
pBuffer = (UINT8*)malloc(size+1);
if(NULL == pBuffer)
{
printf( "not enough memory! \n ");
return FAIL;
}
RetCount = fread(pBuffer, 1, size, hFile);
if(RetCount < size)
{
printf( "read file fail\n ");
free(pBuffer);
fclose(hFile);
return FAIL;
}
fclose(hFile);
------解决方案--------------------
程序的逻辑要严密
异常处理要全面
------解决方案--------------------
hFile = fopen(pFileName, "rb ");
pFileName 这个文件在哪个目录
------解决方案--------------------
取决于你想构建多么健壮的系统。
一般情况下,打开文件后就无需再作太多检查了。
------解决方案--------------------
flttchhy() ( ) 信誉:100
但如此代码似乎不太好看
-----------------------------------
我用C语言或C++读取文件时,是否需要每一次读写都要检查正确性呢,如果读很多次,岂不是要增加许多代码。大家有没有什么好的建议。
下面是我的一段代码,显示非常繁琐:
hFile = fopen(pFileName, "rb ");
if(NULL == hFile)
{
printf( "Open file fail!\n ");
return FAIL;
}
size = fgetsize(hFile);
if(size < 0)
{
printf( "get file size fail!\n ");
fclose(hFile);
return FAIL;
}
if(0 == size)
{
printf( "void file\n ");
fclose(hFile);
return SUCCESS;
}
/*for other ebook*/
if(bufSize > 0)
size = bufSize;
if(size > TEXTBUF_MAXSIZE)
{
printf( "too large file!\n ");
size = TEXTBUF_MAXSIZE-1;
}
pBuffer = (UINT8*)malloc(size+1);
if(NULL == pBuffer)
{
printf( "not enough memory! \n ");
return FAIL;
}
RetCount = fread(pBuffer, 1, size, hFile);
if(RetCount < size)
{
printf( "read file fail\n ");
free(pBuffer);
fclose(hFile);
return FAIL;
}
fclose(hFile);
------解决方案--------------------
程序的逻辑要严密
异常处理要全面
------解决方案--------------------
hFile = fopen(pFileName, "rb ");
pFileName 这个文件在哪个目录
------解决方案--------------------
取决于你想构建多么健壮的系统。
一般情况下,打开文件后就无需再作太多检查了。
------解决方案--------------------
flttchhy() ( ) 信誉:100
但如此代码似乎不太好看
-----------------------------------