CodeNewbie Community 🌱

Discussion on: Reading from a file in C

Collapse
 
djuber profile image
Daniel Uber • Edited

You can use the (short, without path) filename when calling fopen. It will have to already exist in the directory where you run the program when you run the program, or you'll get a null back.

Microsoft's docs have a more complete example, you can see they're calling fopen in the first case like this to read from the source file "crt_fopen.c":

fopen( "crt_fopen.c", "r" )
Enter fullscreen mode Exit fullscreen mode

I think you can specify a complete path as well instead of a short filename, but I'm not 100% sure how to format that correctly for windows (if your C://directory/file format is correct or if something like C:\\\\directory\\file is needed).

One thing to bear in mind is that the path to the file is calculated when fopen is called (at runtime), so the location you're running the program might be different from the location you kept your source code when you built it. This is especially the case if you'll be sharing that program (but not the code) with someone else. The user's current working directory when they start the program becomes the program's working directory when it runs, which during development could be the project directory, but for another user might be anywhere else.