1

I'm trying to (as the title says) read from a file into main, using argc and argv, taking the filename from the command line and passing it through main into a void function which opens, reads and writes it. However im getting Cannot open file... Segmentation fault.

void file_pass (char * argv[])
{

FILE *file_name;
if ((file_name = fopen(argv[1], "r")) == NULL)
    {
        printf("Cannot open file ...\n");
    }

fclose(file_name);

}

Which leads me to think it isn't opening the file correctly but I'm not sure why.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Finlandia_C
  • 385
  • 6
  • 19

1 Answers1

4

In your function void file_pass (char * argv[]) -

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

Instead of this , you should try this -

if ((file_name = fopen(argv[0], "r")) == NULL)   // file's name is in argv[0] in funciton

Because array indexing start with 0 and in function argv[1] may contain nothing .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • 1
    That works perfectly. Strange thought, I thought argv[0] was always the program name, and argv[1] in this case would be the inputted file name? – Finlandia_C Oct 22 '15 at 18:06
  • Ahhh I see. C is so fickle :D – Finlandia_C Oct 22 '15 at 18:10
  • @Finlandia_C Yeah , it may get a little tricky when passing arrays :) – ameyCU Oct 22 '15 at 18:12
  • @Finlandia_C In this copy will not be created as address of `argv[1]` is passed , so `argv[0]` will contain value at that address , that is value of `argv[1]` . The above comment I mentioned is wrong I think . – ameyCU Oct 22 '15 at 18:25