0

I am programming in C and I start to do some basic programming like wordcount in files, but unfortunately I get flaw in my program's execution. The gcc compiler displays such a warning:

test.c: In function ‘main’:
test.c:11: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast
/usr/include/stdio.h:269: note: expected ‘const char * __restrict__’ but argument is of type ‘char’

Line 11 is the line with the if statement

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define FAIL -1 
#define SUCCESS 1

int main (char *filename) {
    FILE *fp;
    char c;
    int wordcount = 0;
    if ((fp = fopen(*filename,"r")) == NULL)
        return FAIL;
    while (!feof(fp))
    {
        while(!isalpha(fgetc(fp)))
        {
            wordcount++;
        }
    }
    printf("wordcount: %d",wordcount);  
    fclose(fp);
    return SUCCESS;
}
timrau
  • 22,578
  • 4
  • 51
  • 64
MIRMIX
  • 1,052
  • 2
  • 14
  • 40

4 Answers4

5

The asterisk when applied before a pointer in C dereferences the pointer, i.e. it evaluates to whatever the pointer points at. You don't want that, you want:

if ((fp = fopen(filename,"r")) == NULL)

Otherwise you're passing a single character (the first character in filename) to fopen(), which expects a pointer to a 0-terminated array of characters (aka "a string").

unwind
  • 391,730
  • 64
  • 469
  • 606
0
int main( int argc, char **argv )
{
  FILE *fp;
  char *path;
  path = argc > 1 ? argv[1] : "default"
  fp = fopen( path, "r" );
  if( fp == NULL ) {
    perror( path );
    exit( EXIT_FAILURE );
  }
  ...
William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

main has to be declared as taking either no argument or (int argc, char* argv[]). And it has to return an int in [0,255], typically either EXIT_SUCCESS or EXIT_FAILURE.

After that, enable warnings in your compiler (gcc -Wall -Werror) and see how it goes.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

By prefixing filename with a '*' you're passing the data filename points to rather than the address where the data is stored - should be:

if ((fp = fopen(filename,"r")) == NULL)

And main only takes the arguments argc and argv. If you're passing the filename as the first argument on the command line, then:

int main (int argc, char* argv[])
{
   FILE *fp;
   char c;
   int wordcount = 0;
   if (argc<1) {
      fprintf(stderr, "need a filename");
      return FAIL;
   }
   if ((fp = fopen(argv[1],"r")) == NULL) {
   ....
symcbean
  • 47,736
  • 6
  • 59
  • 94