user2884579
user2884579

Reputation: 13

segmentation fault in c program that counts characters

I am new to C and trying to write a program that counts brackets, braces, spaces and new lines. The compiler issues the error: Error opening fileSegmentation fault (core dumped)

#include <stdio.h>


int main(int argc, char *argv[])
 {
    FILE *fp;
    char c;
    int blank, tab, openbrace, closedbrace,openbracket,closedbracket, newline=0;


if ((fp = fopen("argv[0]", "r")) == NULL)
   {
     fprintf(stderr, "Error opening file");
    }
 while ((c=fgetc(fp)) != EOF)
 {
switch(c)
    {

        case '{':
        openbrace++;

        case '}':
        closedbrace++;

        case '[':
        openbracket++;

        case ']':
        closedbracket++;

        case '\n':
        newline++;


     }
   }
fclose(fp);
printf("\nThe number of { are %d", openbrace);
printf("\nThe number of } are %d", closedbrace);
printf("\nThe number of [ are %d", openbracket);
printf("\nThe number of ] are %d", closedbracket);
printf("\nThe number of new lines are %d", newline);
}

Upvotes: 1

Views: 99

Answers (3)

vis.15
vis.15

Reputation: 741

The problem is this line:

if ((fp = fopen(argv[0], "r")) == NULL)

argv[0] is the name of the program what you want is argv[1] which is the first user string.

So it should be this:

if ((fp = fopen(argv[1], "r")) == NULL)

Upvotes: 0

Josh B
Josh B

Reputation: 1868

A couple of things:

1) Exit immediately after the error case - don't keep going.

2) Open the argv1, not "argv[0]" (argv[0] holds the executable name, and you were enclosing it in a string)

fopen(argv[1], "r")

It is probably a good idea to make sure argv[1] exists by checking argc too.

Upvotes: 2

akonsu
akonsu

Reputation: 29536

you need to exit the program when you print out the error. Instead, you go into the while loop anyway. and since fp is null, it crashes.

Upvotes: 0

Related Questions