-1

I'm trying to write a program in C where the program will go through the file char by char and print them out to the console. However, when running the code below, I get the error Segmentation fault: 11. Where is the issue in my code?

void readFile(char fileName);

int main(const int argc, char *argv[])
{
    int status = 0;

    for (int i = 1; i < argc; i++) {
        readFile(*argv[i]);
    }

    exit(status);
}

void readFile(char fileName)
{
    FILE* file;
    char c;

    file = fopen(&fileName, "r");

    do {
        c = getc(file);
        printf("%c", c);
        if (!isalpha(c)) {
            printf("\n");
        }
    } while (c != EOF);

    fclose(file);
}
ch1maera
  • 1,369
  • 5
  • 20
  • 42

2 Answers2

3

You are doing it wrong in many level. You passed the 0th character of the i-th argument. You want to pass the whole string. You need to pass char*.

readFile(argv[i]);

You will pass this char* directly to fopen and then check it's return value. Looping could be as simple as

while( (c=getc(file)) != EOF){

}
...
fclose(file);

And you have to use int c instead of char c ensuring that it can hold all the values returned by getc.

user2736738
  • 30,591
  • 5
  • 42
  • 56
1

The signature of your readFile is wrong.

void readFile(char fileName);

readFile is function that expects a single character, not a string. *argv[i] returns the first letter of the string pointed to by argv[i].

void readFile(const char *fileName)
{
    FILE* file;
    int c; // getc returns an int

    file = fopen(fileName, "r");

    // always check for errors
    if(file == NULL)
        return;

    do {
        c = getc(file);
        printf("%c", c);
        if (!isalpha(c)) {
            printf("\n");
        }
    } while (c != EOF);

    fclose(file); // do not forget to close your streams.
}

Note here that your do-while-loop is wrong, because you should check first whether c is EOF. If it isn't then you can print it. It should be:

while((c = getc(file)) != EOF)
{
    putc(c, stdout); // equivalent to printf("%c", c)
    if(!isalpha(c))
        puts("");  // equivalent to printf("\n");
}

Then you can call it like this:

int main(const int argc, char *argv[])
{
    int status = 0;

    for (int i = 1; i < argc; i++) {
        readFile(argv[i]);
    }

    exit(status);
}

Also note that getc returns a int, not a char, so the c variable must be an int.

man fgets

#include <stdio.h>

int getc(FILE *stream);

DESCRIPTION

getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.

RETURN VALUE

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

See also this explanation

Pablo
  • 13,271
  • 4
  • 39
  • 59