Search code examples
ccommand-lineargvargc

Reading a file from command line, name of the file as an argument


i should open and read this file from passing the name of it as an argument of the command line when i run the program, but it keep going through the same error which is the open failure error i set in my program.The file is the correct folder and i also printed the arguments too see the one containing the name of the program wasn't well stored but it was, it's just the fopen function that fails.. Can anybody help me? Here's the code:

 int main(int argc, const char * argv[])
{
if(argc != 2)
{
    fprintf(stderr, "Error: please insert just the name of the file after the one of the program!\n");
    exit(EXIT_FAILURE);
}

FILE *foo;
foo = fopen(argv[1], "r");

if(foo == NULL)
{
    printf("Error: failed to open the file\n Argument: %s\n", argv[1]);
    exit(EXIT_FAILURE);

}

here i leave the screenshots

command line screenshot

how i place the txt file

its position

the program working properly if not run from the cmd line


Solution

  • Here's your problem:

    enter image description here

    Since you passed just the filename to the program, it looks in its current working directory. And as we see from the ls command on the previous command line, there are only two files in the current working directory: main.c and prova. The file ex3.txt is not there.

    Based on the screenshots, it appears that the current working directory for these command lines was ~/documents/computer science xcode project/21:12/ex3/ex3, but the ex3.txt file is actually in the directory <something obscured by pulldown>/ex3-<something>/Build/Products/Debug.

    Apparently the IDE uses that Debug directory, not the ex3 directory, as its current working directory, since it manages to find ex3.txt there without requiring you to provide any directory path in front of the filename.