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

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

file-question. easy.

hello.

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

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é.
0
André123
Asked:
André123
2 Solutions
 
sunnycoderCommented:
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
0
 
cryptosidCommented:
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[]){
FILE *Fp;

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

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


you could then run the command as...

aa.exe ./input.dat

regards,
cryptosid
0
 
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).
0

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