-3

For some odd reason file declaration works differently in Visual Studio than it does in code blocks. The following code runs perfectly fine in code:blocks but won't run in Visual Studio, and I don't have a clue why not Couldn't figure it out.

int n;
FILE * pFile;
pFile = fopen ("date.in","r");
fscanf(pFile,"%d",&n);
printf("%d", n);
return 0;

using cstdio and stdafx respectivly edit 1:

// ConsoleApplication3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int d;
int main ()
{
FILE * inFile;
inFile = fopen("date.in", "r");
fscanf(inFile, "%d", &d);
printf("%d", d);
return 0;
}

Triggers a break point line 1061 of stdio.h

  • 1
    That code won't compile as-is. We need a [mcve] please. – Martin Bonner supports Monica Nov 07 '17 at 20:37
  • Please be more specific than "won't compile". Copy and paste the errors. – molbdnilo Nov 07 '17 at 20:38
  • I have restored the C++ tag. There is no cstdio header in C, but there is in C++. (You may argue that this code could perfectly well have been written in C, and I would agree, but it hasn't been.) – Martin Bonner supports Monica Nov 07 '17 at 20:41
  • My crystal ball thinks that you should read [this Q & A](https://stackoverflow.com/questions/10460250/cstdio-stdio-h-namespace) about `` and the global namespace. – molbdnilo Nov 07 '17 at 20:42
  • @molbdnilo : Your crystal ball is on the fritz. Using cstdio worked!. So presumably it put `fopen` in the global namespace too - which is allowed but not required. Alternatively, there is a `using namespace std;` (spit) which the OP is not telling us about.. – Martin Bonner supports Monica Nov 07 '17 at 20:44
  • 2
    I expect the problem is the file was not found but you still attempt to read from it. This has nothing to do with compiling. – drescherjm Nov 07 '17 at 20:47
  • 1
    Remember that the default folder when debugging / running in Visual Studio is the folder containing the project file not the executable. That is unless you modified the default settings in Visual Studio. – drescherjm Nov 07 '17 at 20:49
  • I have edited your question to change "compile" to "run". If you are hitting a breakpoint, the program compiled - it just didn't run properly. If this is wrong, please [edit] your question to give more detail. – Martin Bonner supports Monica Nov 07 '17 at 20:49

1 Answers1

2

The problem is that you don't check the result of fopen, and it has failed. This is almost certainly because data.in is not in the current directory when the program runs (but is some other directory)

You can specify the current directory for when you run the program in the project properties. Alternatively, pass the full path of the datafile on the command line, and specify the arguments to the program in the project properties.