为什么我会断言失败?
当我尝试使用 VC2010 调试此代码时失败:
This code fails when I try to debug it using VC2010:
char frd[32]="word-list.txt";
FILE *rd=fopen(frd,"r");
if(rd==NULL)
{
std::cout<<"Coudn't open file "<<frd;
exit(1);
}
char readLine[100];
while(fgets(readLine, 100, rd) != NULL)
{
readLine[strlen(readLine) - 1] = ' ';
char *token = NULL;
token = strtok(readLine, " ,");
insert(readLine);
}
调试结果
--------------------------- Microsoft Visual C++ 调试库-----------
--------------------------- Microsoft Visual C++ Debug Library-----------
调试断言失败!
程序:...documentsvisual studio 2010ProjectsfaDebugfa.exe文件:f:ddvctoolscrt_bldself_x86crtsrcfgets.c 行:57
Program: ...documentsvisual studio 2010ProjectsfaDebugfa.exe File: f:ddvctoolscrt_bldself_x86crtsrcfgets.c Line: 57
表达式:( str != NULL )
Expression: ( str != NULL )
有关您的程序如何导致断言失败的信息,请参阅有关断言的 Visual C++ 文档.
For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.
(按重试调试应用程序)
(Press Retry to debug the application)
我得到的错误号是 2;
The errno I get is 2;
我的猜测是文件无法打开,而您仍在将其传递给 fgets.如果 fgets 为空,则您的 if(rd==NULL) 不会停止执行,它只是打印出一条消息并继续执行.
My guess is that the file is failing to open, and you're still passing it to fgets. Your if(rd==NULL) doesn't stop execution of the fgets if it's null, it just prints out a message and continues with execution.
一些非常基本的错误处理:
Some very basic errorr handling:
const char* frd = "word-list.txt";
FILE *rd=fopen(frd,"r");
if(rd==NULL) {
std::cout<<"Coudn't open file"<<endl;
return 1;
}
char readLine[100];
while(fgets(readLine, 100, rd) != NULL)
{
readLine[strlen(readLine) - 1] = ' ';
char *token = NULL;
token = strtok(readLine, " ,");
insert(readLine);
}