Home > Software design >  Passing filename as argument causing segmentaion fault when the file is not found
Passing filename as argument causing segmentaion fault when the file is not found

Time:10-03

I want to open a file by taking the filename as a command-line argument and then passing it to a function.

The code works perfectly fine when the file is opened, but it throws a segmentation fault error message when the file is not found. It also works when I shift the file opening logic from the runFile function to main function but it is causing segmentation fault when the filename is passed as an argument to the function.

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

void runFile(char* fileName);

int main(int argc, char** argv)
{   
    if (argc != 2)
    {   
        printf("Usage: ./lexer [source]\n");
        exit(64);
    }
    else
    {   
        runFile(argv[1]);
    }
    return 0;
}

void runFile(char* file)
{
    FILE *fp;
    if (!filename)
    {
        printf("Error");
    }

    fp = fopen(file, "r");
    if ((fp = fopen(file, "r")) == NULL)
    {
        printf("File not opened!");
    }
    else
    {
        printf("File opened Successfully!\n");
    }



    fclose(fp);
}

CodePudding user response:

Write your runFile() function like this:

void runFile(char* file) {
  FILE* fp = fopen(file, "r");

  if (fp == NULL) {
    printf("File not opened!\n");
    return;
  }

  // do something with the file
  printf("File opened!\n");

  fclose(fp);
}

The problem with your code was that you still called fclose(fp) even when fp was NULL (because it could not open the file); fclose(fp) should be called only once and only when fp != NULL.

  • Related