0
votes

I have made a simple file reading program that runs successfully in DEV C gcc compiler, but it shows an error Debug Assertion Failed. I searched and someone has asked the same question 12 days ago, answer shows that his error was on the statement

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

and says the separate the two statements as

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

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

My Code

#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;
}    `

My Error

Debug Assertion failed! Program: ...o 2015\Projects\Let Us C Solutions\Debug\Let Us C Solutions.exe File: minkernel\crts\src\appcrt\stdio\fgetc.cpp Line: 43 Expression: stream.valid() For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press Retry to debug the application)

1
Did fopen fail and fpis NULL? - Rabbid76
No!, fopen is not failed as fp is not NULL, because I have run the same program on other compiler, that runs successfully - Siraj Alam
How do you know fp is not NULL when you run the program on this computer, though? - user253751
if (ch == NULL) { printf("The file didn't opened\n"); break; } change to if (fp == NULL) { printf("The file didn't opened\n"); } and move to after fp = fopen("Sarju.txt", "r"); - BLUEPIXY
also if (ch != NULL) fclose(fp); --> if (fp != NULL) fclose(fp); - BLUEPIXY

1 Answers

0
votes

Your code has several problems. The corrected code would be:

#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. I used int as fgetc returns an int, not char.
  2. You should check if fp is not NULL, not ch.
  3. ch = fgetc(fp); was at the wrong place.