Segmentation fault when writting full location of the file

1419 views c

Quick question This code gives me Segmentation fault error

f = fopen("~/proj/viagens.txt", "r");

But this one doesnt

f = fopen("viagens.txt", "r");

Why's that?

answered question

Does fopen lead to a segmentation fault, or don't you check the return value and just used it? In the latter case the question should be why you can not open this file.

No, fopen() doesn't give you a segmentation fault error. The code that you didn't post that uses f after fopen() failed and you didn't check for errors is what's giving you a segmentation fault.

1 Answer


~ is a notation that is expanded by your shell (e.g. Bash) into your home directory, so if you invoke a program like vim ~/proj/viagens.txt, the shell will expand the parameter into /home/ventura/proj/viagens.txt before the program vim ever sees it. ~ is not understood by fopen, which requires an absolute path path or a path relative to the current working directory.

(As @Osiris and @AndrewHenle point out in their comments, fopen doesn't segfault, but it will return null when it can't find the file, which will cause a segfault down the line when you try to use f as a file descriptor.)

posted this

Have an answer?


Please login first before posting an answer.