Oria Gruber
Oria Gruber

Reputation: 1533

counting characters in a file in C - very basic

This is my first time in a while working with files, and while I get the general idea, I have some problems implementing simple algorithms.

For example, I'm trying to write a code that counts number of characters in a given file. Number of letters.

This is my code:

#include<stdio.h>
FILE *fp;
void main()
{
    int counter=0;
    fp=fopen("G:\hellostackoverflow.txt","r");
    while(fgetc(fp)!=EOF)
        counter++;
    printf("there are %d letters", counter);
}

When I run it, I run into an error, something along the lines of:

Debug assertion failed!

Expression(stream!=NULL)

For information on how...

Why does this happen and how can I fix it?

Upvotes: 1

Views: 751

Answers (1)

hugomg
hugomg

Reputation: 69924

Sounds like your program is not being able to read the input file. You should always check fopen for null to detect this sort of problem

fp=fopen("G:\hellostackoverflow.txt","r");
if(fp == NULL){
     printf("could not open file\n");
     return 1;
}

My guess is that the problem is the un-escaped backslash in the pathname. Try escaping it "G:\\hellostackoverflow.txt" or moving your file to a different location that does not require backslashes.

Upvotes: 4

Related Questions