请问一个关于指针的有关问题
请教一个关于指针的问题。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int Get_Config(char *lpFileName,char *SerchBuf,char *szTmp)
{
FILE *stream;
char pBuf[256]= " ";
char *p;
char *ptoken = NULL;
if((stream=fopen(lpFileName, "rt "))== NULL )
{
printf( "opne file is error\n ");
return -1;
}
while(!feof(stream))
{
memset(pBuf, 0x00, 256);
fgets(pBuf, 256, stream);
if(strstr(pBuf,SerchBuf))
{
p = strchr(pBuf, '= ');
strncpy(szTmp, p + 1, sizeof(pBuf));
printf( "this is very important data %s\n ",szTmp);
break;
}
else
continue;
}
fclose(stream);
return 1;
}
int main()
{
char lpFileName[128]= "Config.ini ";
char szTmp[128];
memset(szTmp, 0x00, 128);
if(Get_Config(lpFileName, "TMP_LEN= ",szTmp)==-1)
{
printf( "get config error\n ");
}
printf( "this TMP_LEN is %s\n ",szTmp);
getchar();
return 0;
}
我执行这个程序的时候,能够正确的读取一次配置文件的内容,但是第2次调用上面的这个Get_Config函数,就不能正常打开lpFileName文件了。这时显示为opne file is error。请问各位大虾扎个整哦?
------解决方案--------------------
strncpy(szTmp, p + 1, sizeof(pBuf));
-------------------------------------
这一行的问题,szTmp你只定义了128字节大小,拷贝用了sizeof(pBuf)=256,产生越界操作,把文件名区域都覆盖了,没有文件名,第二次当然打不开文件了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int Get_Config(char *lpFileName,char *SerchBuf,char *szTmp)
{
FILE *stream;
char pBuf[256]= " ";
char *p;
char *ptoken = NULL;
if((stream=fopen(lpFileName, "rt "))== NULL )
{
printf( "opne file is error\n ");
return -1;
}
while(!feof(stream))
{
memset(pBuf, 0x00, 256);
fgets(pBuf, 256, stream);
if(strstr(pBuf,SerchBuf))
{
p = strchr(pBuf, '= ');
strncpy(szTmp, p + 1, sizeof(pBuf));
printf( "this is very important data %s\n ",szTmp);
break;
}
else
continue;
}
fclose(stream);
return 1;
}
int main()
{
char lpFileName[128]= "Config.ini ";
char szTmp[128];
memset(szTmp, 0x00, 128);
if(Get_Config(lpFileName, "TMP_LEN= ",szTmp)==-1)
{
printf( "get config error\n ");
}
printf( "this TMP_LEN is %s\n ",szTmp);
getchar();
return 0;
}
我执行这个程序的时候,能够正确的读取一次配置文件的内容,但是第2次调用上面的这个Get_Config函数,就不能正常打开lpFileName文件了。这时显示为opne file is error。请问各位大虾扎个整哦?
------解决方案--------------------
strncpy(szTmp, p + 1, sizeof(pBuf));
-------------------------------------
这一行的问题,szTmp你只定义了128字节大小,拷贝用了sizeof(pBuf)=256,产生越界操作,把文件名区域都覆盖了,没有文件名,第二次当然打不开文件了。