Reputation: 27
The lecturer uploaded a text file called file.txt and this resulted in a file "file.txt.txt"... I am feeling a mix of frustration and stupidity right now.
I'm having trouble with C using Visual Studio 2012 on Windows 7 trying to open a text file using fopen. I'm not too sure which directory this file.txt should be in so I tried placing it with the .vcxproj file AND the .exe file which is in the Debug directory created by VS.
With no success, I tried including the full path to the file in the fopen function.
This code compiles fine but when I run it, I get an error saying "No such file or directory"
What am I doing wrong and how can I fix it? I'm really confused here and any help would be most welcome! Thanks in advance.
Code below:
int main(void)
{
FILE *fp;
fp = fopen("C:\\Directory\\file.txt", "r");
if (fp == NULL)
{
perror("Error opening file\n");
}
return 0;
}
Upvotes: 1
Views: 20708
Reputation: 399823
You should include the proper header for fopen()
, which is
#include <stdio.h>
Make sure all the backslashes are really escaped (doubled) in your filename, too.
Upvotes: 0
Reputation: 6514
Do you really have any file at this place "C:\Directory\file.txt" I guess you do not have one.
I tried the code and it runs perfectly fine for me. Initially I was getting the same error and that was because the file was not there. Once I put the file there, it all worked perfectly as expected.
Please check again that the file is in place.
Upvotes: 1