Pergunta

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);
}
Foi útil?

Solução 2

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)

Outras dicas

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.

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top