2016-01-16 57 views
0

我已经制作了一个简单的文件读取程序,可以在DEV C gcc编译器中成功运行,但它显示错误Debug Assertion Failed。 我搜索,有人问同样的问题12天前, 的回答表明,他的错误是在声明Visual Studio 2015显示调试断言失败

if (file = fopen (name, "w+") == NULL) { 
    ... 
}  

,并表示单独的两个语句

file = fopen(name, "w+"); 

if (fp == NULL) { ...}  

我的代码

#include<stdio.h> 
#include<conio.h> 
#include<stdlib.h> 
int main() 
{ 

    int nos = 0, noc = 0, nol = 0; 
    char ch; 
    FILE *fp; 
    fp = fopen("Sarju.txt", "r"); 
    while (1) 
    { 
     ch = fgetc(fp); 
     if (ch == NULL) 
     { 
      printf("The file didn't opened\n"); 
      break; 
     } 
     if (ch == EOF) 
      break; 
     noc++; 
     if (ch == ' ') 
      nos++; 
     if (ch == '\n') 
      nol++; 
    } 
    if (ch != NULL) 
     fclose(fp); 
    printf("Number of Space : %d\nNumber of Characters : %d\nNumber of lines : %d\n", nos, noc, nol); 
    _getch(); 
    return 0; 
} ` 

我的错误

Debug Assertion failed! Program:... o 2015 \ Projects \让我们C Solutions \ Debug \让我们C Solutions.exe文件:minkernel \ crts \ src \ appcrt \ stdio \ fgetc.cpp行:43表达式:stream.valid()有关程序如何导致断言失败的信息,请参阅断言上的Visual C++文档。 (按重试以调试应用程序)

+2

'fopen'失败,'fp'是'NULL'? – Rabbid76

+0

不!!fopen不是失败的,因为fp不是NULL,因为我在其他编译器上运行了相同的程序,运行成功 – Siraj

+1

如何在* this *上运行程序时知道'fp'不为NULL?电脑,但? – immibis

回答

0

您的代码有几个问题。更正后的代码将是:

#include <stdio.h> 
#include <conio.h> 
#include <stdlib.h> 

int main() 
{ 
    int nos = 0, noc = 0, nol = 0; 
    int ch; /* `int`, not `char` */ 
    FILE *fp; 
    fp = fopen("Sarju.txt", "r"); 
    while (1) 
    { 
     /*ch = fgetc(fp); After the below `if`, not here */ 
     if (fp == NULL) /* `fp`, not `ch` */ 
     { 
      printf("The file didn't opened\n"); 
      break; 
     } 
     ch = fgetc(fp); 
     if (ch == EOF) 
      break; 
     noc++; 
     if (ch == ' ') 
      nos++; 
     if (ch == '\n') 
      nol++; 
    } 
    if (fp != NULL) /* `fp`, not `ch` */ 
     fclose(fp); 
    printf("Number of Space : %d\nNumber of Characters : %d\nNumber of lines : %d\n", nos, noc, nol); 
    _getch(); 
    return 0; 
} 
  1. 我以前intfgetc返回int,不char
  2. 您应该检查fp是不是NULL,而不是ch
  3. ch = fgetc(fp);是在错误的地方。