灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:3271回复:0

用c语言写的读一行源代码

楼主#
更多 发布于:2013-02-19 14:19
因为工作需要,用c语言写了一个读一行的函数,供大家参考:
[cpp]  
static BOOL readLine(FILE* file, char** ppBuf)  
   {  
   int   nMax = 128;  
   char  szBuf[128];  
   char* pAmountBuf = NULL ;  
   char* pResult;  
   int   nLen = 0;  
   int   nAmountLen = 0;  
   char* pTmp;  
   BOOL  bLoop = TRUE;  
   do  
   {  
       pResult=fgets(szBuf, nMax, file);  
       /* handle error */  
       if( pResult == NULL ;; !feof(file) )  
           {  
           if( pAmountBuf )  
               free( pAmountBuf);  
           return FALSE;  
           }  
       if( pResult == NULL )  
           {  
           break;  
           }  
       else if ( (nLen = strlen( szBuf )) < nMax-1 ||  
               szBuf[nLen-1] == '\n'  
               )  
           {  
           if( nLen ==0 )  
               break;  
           bLoop = FALSE;  
           }  
       nAmountLen += nLen;  
       pTmp = (char*)malloc( sizeof(char)* (nAmountLen + 1) );  
       if( pTmp == NULL )  
           {  
           if( pAmountBuf )  
               free ( pAmountBuf );  
           return FALSE;  
           }  
       if( pAmountBuf )  
           {  
           strcpy(pTmp, pAmountBuf );  
           strcat(pTmp, szBuf);  
           }  
       else  
           {  
           strcpy(pTmp, szBuf);  
           }  
       pAmountBuf = pTmp;  
   }  
   while( bLoop );  
     
   if( nAmountLen!=0 ;; pAmountBuf[nAmountLen-1] == '\n' )  
       {  
       pAmountBuf[--nAmountLen]=0;  
       }  
   if( nAmountLen!=0 ;; pAmountBuf[nAmountLen-1] == '\r' )  
       {   www.atcpu.com
       pAmountBuf[--nAmountLen]=0;  
       }  
   if( nAmountLen==0 )  
       {  
       if( pAmountBuf )  
           free( pAmountBuf );  
       }  
   else  
       *ppBuf=pAmountBuf;  
   return nAmountLen!=0;  
     
   }

喜欢0 评分0
游客

返回顶部