Calvin1602
Calvin1602

Reputation: 9547

'fopen' fails if the file opened in Visual Studio

I have the following code:

FILE *fp = fopen( srcFile.filename.c_str(), "rt");

srcFile happens to be the solution's main.cpp file, and thus is opened in the solution. fopen returns NULL most of the time (but not when I step into it, which is weird).

However, when I close main.cpp in Visual Studio, the code works. Even when the file is opened in Notepad++.

Is there a workaround?

PS: I tagged it as C, but the file is compiled as C++, IDK if it changes anything.

Upvotes: 1

Views: 4479

Answers (2)

nategoose
nategoose

Reputation: 12392

I think that this may have to do with the working directory (folder) being different when running within Visual Studio. If this is the case then using an absolute path to the file ("C:\folder\other-folder\file.txt") instead of a relative path ("file.txt") should make it work.

Upvotes: 1

user411313
user411313

Reputation: 3990

Let C print the errormessage:

FILE *fp = fopen( srcFile.filename.c_str(), "rt" );
if( !fp ) 
{
  perror( srcFile.filename.c_str() );
  exit( 1 );
}

Upvotes: 0

Related Questions