0

I'm making a function to count the number of words in a file but as soon as it reaches the fscanf the program crashes with the aforementioned return value.

i'm making a program to build a binary tree and i thought at first that it's crashing because of some pointer error or something but i commented out the rest of the code and it still gives the error;

include stdio.h
include stdlib.h
include string.h
FILE *file;
typedef struct Node{

struct Node* left;
struct Node* right;
struct Node* parent;
char *word;

}Node;

typedef struct{

Node* root;
int maxlen;

}tree;


int getCount()
{
    int count=0;
    file=fopen("hi.txt","r");
    while(!feof(file))
    {

        count++;
        fscanf(file,"%s\n");

    }
    fclose(file);
    return count;
}

int main()
{
    int count=getCount();
    printf("count=%d",count);

    /*tree t;

    buildbase(&t,getMaxmin(count),count);*/



return 0;
}

the code worked yesterday and i didn't change anything in this function and it produced 98915

Saladin
  • 3
  • 1
  • 1
    You use `fscanf` in the code you show. Have you ever used the closely related `scanf` function? To read strings using the `"%s"` format specifier? – Some programmer dude Apr 23 '19 at 06:00
  • On an unrelated issue, please read [Why is “while (!feof(file))” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) and learn what [`scanf` (and siblings) *return*](https://en.cppreference.com/w/c/io/fscanf#Return_value). – Some programmer dude Apr 23 '19 at 06:01
  • Oh, and stop using global variables! Define variables only in the functions that use the variables. And if you need to pass values to a function, pass it as arguments. – Some programmer dude Apr 23 '19 at 06:01
  • BTW: you should consider what happens if the "hi.txt" does not exist. – Jabberwocky Apr 23 '19 at 07:29

1 Answers1

3

There is no variable you are assigning string read by fscanf, it should be more like:

int getCount()
{
    int count=0;
    char buffer[1024] = { 0 };
    file=fopen("hi.txt","r");
    while(!feof(file))
    {

        count++;
        fscanf(file,"%s\n", buffer);

    }
    fclose(file);
    return count;
}
Diodacus
  • 663
  • 3
  • 8