## CodeNewbie Community is a community of 5,559 amazing newbies

Christopher Cooper

Posted on

# Reading from a file in C

Can anyone recommend a resource on reading files in C?

Do you know if I place the .txt file in the same file as the project do I have to include the entire directory in the fopen() or just the file name as in the folder?

For example, do I need fopen("C//:programmingFile/myFile", "r"); or can I just have fopen("myFile", " r");?

## Discussion (2)

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" )


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.

Christopher Cooper

Thank you so much, Daniel, this helps a lot!