IC2D
IC2D

Reputation: 501

Why am I getting a seg fault (strcmp or fgets)?

I don't understand why I am getting a seg fault with this small amount of code. I don't know whether it is strcmp or fgets this is causing the problem. I've been working on and off for two days with this, pardon my frustration.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{

FILE* input;
char line[40];


    printf("%s\n", argv[1]);
    if ((strcmp(argv[1], "-f")) == 1)
    {           
        printf("Inside first if statement\n");          
        input = fopen(argv[2], "r");
        if(input == NULL)           
        {
            printf("Could not open file\n");
            exit(-1);
        }
    }
    while ((fgets(line, 40, input)) != NULL)
        {
        //printf("%s\n", input_line);
        }

return 0;
}

Upvotes: 0

Views: 345

Answers (2)

ChuckCottrill
ChuckCottrill

Reputation: 4444

You might want to do the following:

  • check the number of arguments
  • allocate room in line[] for the NULL-terminator
  • strcmp returns =0 on success, >0 location of mismatch
  • perl has 'chomp', you might replicate it to remove extra "\n"

Here is your code, revised and working,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int usage()
{
    printf("usage: %s -f <file>\n",argv[0]);
}

int main(int argc, char* argv[])
{
    FILE* input;
    char line[+1]; //allow room for NULL terminator

    if (argc < 3 || strcmp(argv[1], "-f") ) { usage(); exit(1); }
    printf("file: %s\n", argv[2]);
    if( (input = fopen(argv[2], "r")) == NULL)
    {
        printf("open %s\n",argv[2]);
        exit(2);
    }
    //ask C how big line[] is
    while ( fgets(line, sizeof(line), input) != NULL )
    {
        //line[sizeof(line)-1] = '\0'; //fgets does this for us
        printf("%s\n", line);
    }
    return 0;
}

BTW: *The use of EXIT_SUCCESS and EXIT_FAILURE is slightly more portable (to non-UNIX environments) than the use of 0 and some nonzero value like 1 or -1.*

Upvotes: 1

LihO
LihO

Reputation: 42133

if ((strcmp(argv[1], "-f")) == 1)

should be:

if (strcmp(argv[1], "-f") == 0)

...you might want to read the documentation first. See strcmp, fgets.

Upvotes: 4

Related Questions