[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 190
  • Last Modified:

file-question. easy.


I made this code:
#include <iostream>
#include <windows.h>
using namespace std;
int main(){
Fp = fopen("input.dat","r");
if (Fp == NULL) {
  fprintf(stderr, "Can't open input file!\n");

I have input.dat (version 1) located at:
"C:\\Program Files\\Microsoft Visual Studio\\MyProjects\\inlezenvanbestand\\input.dat"

and my program is here:
"C:\\Program Files\\Microsoft Visual Studio\\MyProjects\\inlezenvanbestand\\release\\aa.exe"

I have allso a input.dat (version 2) located here:
"C:\\Program Files\\Microsoft Visual Studio\\MyProjects\\inlezenvanbestand\\release\\input.dat"
version 1 of input.dat is different from version 2.

The strange thing is:
when I run my program it opens version 1 of input.dat  .
I want it to open the version in the directory of the exe (version 2).

so, my questions:
(1)-> How should I adapt the code so that it allways opens the file that is placed in the directory of the program itself (and,  I don't want to have the file-pad "hardcoded" in the exe)
(2)-> How comes it opens the version 1 file ?? I don't think this is very logic , since it is placed one directory up !

Any advice is welcome...

Greetz, André.
2 Solutions
The program looks in for the file in its "current working directory". If you change your directory programatically, your code would look for files in the new directory and not in the one where it was created/launched. There apparently is no other reason why version 1 is opened instead of version 2
Try using commandline parameters option.. here below .. argc will contain the total number of parameters specified at command line and *argv[] will contain the list of arguments.

int main(int argc, char *argv[]){

if (argc!=1)
 Fp = fopen(argv[1],"r");
Fp = fopen("input.dat","r");

if (Fp == NULL) {
  fprintf(stderr, "Can't open input file!\n");

you could then run the command as...

aa.exe ./input.dat

André123Author Commented:
thanks both.

Tried it in some other folders and it opens the correct version if I don't run it from MSVC (so, from a cmd-promt).

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now