Thread: segmentation fault when opening a file

  1. #1
    Registered User
    Join Date
    Jan 2023
    Posts
    5

    segmentation fault when opening a file

    hi guys! pretty new here, just wanted to ask if someone can save me another 5hrs of research - what could cause segmentation fault while i open a file?
    ps: it is in the same directory, and i tried entering whole path while starting program,.. nothing helps

    thank you A LOT

    here is the code:
    Code:
    int main(int argc, char *argv[])
    {
      char *file_name = argv[1];
      if (argc != 2) {
        printf("Usage: ./a4 %s\n", file_name);
        return 1;
      }
      FILE *config_file = fopen(argv[1], "r");
      if (config_file == NULL) {
        printf("Error: Cannot open file: %s\n", file_name);
        return 2;
      }
      printf("opened");
    
      fclose(config_file);
      return 0;
    }
    Last edited by Salem; 01-15-2023 at 12:07 AM. Reason: removed crayola

  2. #2
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103
    What does this code do?
    Code:
    if (argc != 2)
    {
    printf("Usage: ./a4 %s\n", file_name);
    return1;
    }
    First you check if the argument counter is not equal to 2 and then use the second argument....

  3. #3
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Quote Originally Posted by smilaf99 View Post
    hi guys! pretty new here, just wanted to ask if someone can save me another 5hrs of research - what could cause segmentation fault while i open a file?
    ps: it is in the same directory, and i tried entering whole path while starting program,.. nothing helps

    thank you A LOT
    First, always post your code as plain text without the colors.

    Second, Compare my code below with your code:
    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
      if (argc != 2)
      {
        printf("Usage: ./a4 file\n");
    
        return 1;
      }
    
      FILE *config_file = fopen(argv[1], "r");
      if (config_file == NULL)
      {
        printf("Error: Cannot open file: %s\n", argv[1]);
        return 2;
      }
      printf("opened\n");
    
      fclose(config_file);
    
      return 0;
    }
    Third, if you start the program without an input file, your first line in main() will or should assign NULL. Note the changes I also made.

    Lastly, use indentation to make the code clear. Choose an indentation style and stick to it.

    My version of your code works for me on Linux with gcc.

  4. #4
    Registered User
    Join Date
    Jan 2023
    Posts
    5
    Quote Originally Posted by G4143 View Post
    What does this code do?
    Code:
    if (argc != 2)
    {
    printf("Usage: ./a4 %s\n", file_name);
    return1;
    }
    First you check if the argument counter is not equal to 2 and then use the second argument....
    it is a snippet of code in which the error occurs.. and yes, i need exactly 2 arguments given, so im returning error value if it has more/less... i dont understand whats not clear

  5. #5
    Registered User
    Join Date
    Jan 2023
    Posts
    5
    Quote Originally Posted by rstanley View Post
    First, always post your code as plain text without the colors.

    Second, Compare my code below with your code:
    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
      if (argc != 2)
      {
        printf("Usage: ./a4 file\n");
    
        return 1;
      }
    
      FILE *config_file = fopen(argv[1], "r");
      if (config_file == NULL)
      {
        printf("Error: Cannot open file: %s\n", argv[1]);
        return 2;
      }
      printf("opened\n");
    
      fclose(config_file);
    
      return 0;
    }
    Third, if you start the program without an input file, your first line in main() will or should assign NULL. Note the changes I also made.

    Lastly, use indentation to make the code clear. Choose an indentation style and stick to it.

    My version of your code works for me on Linux with gcc.
    TBH i dont see anything changed.. just the indentation - which got deleted when i copy-pasted the code here.. so if it works for you, then the code is not the problem but the text file... thanks!

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Sorry... edited...

  7. #7
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    As rstanley explained you are using argv[1] BEFORE testing if it is valid:
    Code:
      // Here! What happens if argc == 1?
      char *file_name = argv[1];
    
      if (argc != 2) {
        printf("Usage: ./a4 %s\n", file_name);
        return 1;
      }
      ...
    You should:
    Code:
      char *file_name;
    
      if (argc != 2) {
        printf("Usage: ./a4 %s\n", file_name);
        return 1;
      }
    
      file_name = argv[1];
      ...

  8. #8
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Quote Originally Posted by flp1969 View Post
    As rstanley explained you are using argv[1] BEFORE testing if it is valid:
    Code:
      // Here! What happens if argc == 1?
      char *file_name = argv[1];
    
      if (argc != 2) {
        printf("Usage: ./a4 %s\n", file_name);
        return 1;
      }
      ...
    You should:
    Code:
      char *file_name;
    
      if (argc != 2) {
        printf("Usage: ./a4 %s\n", file_name);
        return 1;
      }
    
      file_name = argv[1];
      ...
    Wrong!
    In the second example, file_name is an uninitialized char pointer! What gets printed in the printf() if "argc != 2"??? Garbage!

    See my code above for the preferred method!

  9. #9
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Quote Originally Posted by smilaf99 View Post
    TBH i dont see anything changed.. just the indentation - which got deleted when i copy-pasted the code here.. so if it works for you, then the code is not the problem but the text file... thanks!
    Again, don't attempt to access argv[1] BEFORE you test if you passed a filename!

    Your code:
    Code:
      char *file_name = argv[1];
      if (argc != 2) {
        printf("Usage: ./a4 %s\n", file_name);
        return 1;
      }
    My code:
    Code:
      if (argc != 2)
      {
        printf("Usage: ./a4 file\n");
     
        return 1;
      }
    You don't need "file_name" at all, just use argv[1] where appropriate. Compare my code to yours again.

  10. #10
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Quote Originally Posted by rstanley View Post
    Wrong!
    In the second example, file_name is an uninitialized char pointer! What gets printed in the printf() if "argc != 2"??? Garbage!

    See my code above for the preferred method!
    Ooops! My bad! You are right: The 3rd argument of fprintf, below, should be argv[0], as this:

    Code:
    if ( argc != 2 )
    {
      fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
      return EXIT_FAILURE;
    }

  11. #11
    Registered User
    Join Date
    Sep 2020
    Posts
    425
    This is a somewhat lame point, but you can't always trust argv[0] to not be NULL.

    I've got two programs - 'b' that prints out if the first argv is NULL, and 'a' that calls it with no command line args.

    Here's the code for 'b.c'
    Code:
    #include <stdio.h>
    
    
    int main(int argc, char *argv[]) {
    
    
       printf("%i args\n",argc);
       if(argv[0] == NULL) {
          printf("argv[0] is NULL\n");
       }
       return 0;
    }
    Here's the code for 'a.c', that execs 'b' without ANY command line args:

    Code:
    #include <stdio.h>
    #include <unistd.h>
    
    
    char * const args[] = {
        NULL
    };
    char *env[] = {
        NULL
    };
    
    
    int main(int argc, char *argv[]) {
       execve("./b", args, env);
       fprintf(stderr, "Exec failed\n");
       return 0;
    }

  12. #12
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Quote Originally Posted by hamster_nz View Post
    This is a somewhat lame point, but you can't always trust argv[0] to not be NULL.
    ...
    Code:
    #include <stdio.h>
    #include <unistd.h>
    
    char * const args[] = {
        NULL
    };
    char *env[] = {
        NULL
    };
    
    
    int main(int argc, char *argv[]) {
       execve("./b", args, env);
       fprintf(stderr, "Exec failed\n");
       return 0;
    }
    Ahhhh... this is a very interesting point. Never thought about it this way, thanks hamster_nz!

    Very interesting indeed! In my distro argv[0] is substituted by "". Using MSys2 or Cygwin exec??() fails, but it works on Linux. Of course, the only garantee is argv[argc]==NULL.
    Last edited by flp1969; 01-16-2023 at 06:22 AM.

  13. #13
    Registered User
    Join Date
    Jan 2023
    Posts
    5
    Quote Originally Posted by rstanley View Post
    Again, don't attempt to access argv[1] BEFORE you test if you passed a filename!

    Your code:
    Code:
      char *file_name = argv[1];
      if (argc != 2) {
        printf("Usage: ./a4 %s\n", file_name);
        return 1;
      }
    My code:
    Code:
      if (argc != 2)
      {
        printf("Usage: ./a4 file\n");
     
        return 1;
      }
    You don't need "file_name" at all, just use argv[1] where appropriate. Compare my code to yours again.
    yes, yes - i noticed a little while after replying, just because i focused more on the file opening part.. i usually test-case it with exactly 2 arguments, just like test cases our class provides.. so i kinda ignored it.. good point, i fixed it right after

  14. #14
    Registered User
    Join Date
    Jan 2023
    Posts
    5
    indeed, i catch myself adjusting too much to my class' test cases (like i told in a reply before), than thinking outside of the box and going for the most efficient code overall - so not a lame point at all haha

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading file in but receive segmentation fault
    By RozenKristal in forum C Programming
    Replies: 3
    Last Post: 09-29-2013, 07:08 AM
  2. Reading from file, segmentation fault
    By atac in forum C Programming
    Replies: 2
    Last Post: 05-08-2013, 10:34 PM
  3. Segmentation fault in Header file
    By Marc Oleson in forum C Programming
    Replies: 12
    Last Post: 04-26-2013, 05:39 PM
  4. Segmentation Fault. When trying to open file.
    By guyle in forum C Programming
    Replies: 5
    Last Post: 02-25-2013, 12:55 PM
  5. Segmentation fault with a file pointer?
    By Matt13 in forum C Programming
    Replies: 14
    Last Post: 07-31-2004, 05:53 AM

Tags for this Thread