Originally Posted by
smilaf99
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.