-1

I have the following C++ code in a subdirectory of my project: /storage/app/users/user1/12/12.cpp

#include <bits/stdc++.h>
using namespace std;

main(){
    int x,y,z,t;
    freopen("input.txt","r",stdin);
    cin >> x >> y >> z >> t;
    cout << x <<" "<< y <<" "<<z <<" "<<t;
}

This code is then compiled into a .exe file: /storage/app/users/user1/12/12.cpp.exe.

The input.txt file is in the same directory with the 2 given files and contains

1 2 3 4

When I tried to run 'cd storage/app/users/user1/12 ; ./12.cpp.exe', it produced the expected output: 1 2 3 4

But when I tried to run it directly: './storage/app/users/user1/12/12.cpp.exe', it produced such a strange output: 0 4254553 0 1

Why is it happening?

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Hoàng Tùng
  • 100
  • 1
  • 2
  • 10
  • 1
    HInt: what's the *current* path in each case? Which `input.txt` file is loaded in each case since you use a *relative* path? – Panagiotis Kanavos Jul 08 '19 at 16:25
  • 1
    In case 1 it tries to open `storage/app/users/user1/12/input.txt` and in case 2 it tries to open `./input.txt`. This has almost nothing to do with C++, this is about system paths and how they work. – nada Jul 08 '19 at 16:25
  • https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h –  Jul 08 '19 at 16:25
  • Also please don't [`#include `](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – nada Jul 08 '19 at 16:26
  • 1
    You'd have the same problem in Linux and Mac OS too. – Panagiotis Kanavos Jul 08 '19 at 16:26
  • [freopen](https://en.cppreference.com/w/cpp/io/c/freopen) has a return value for a reason. You need to think about error checking in your code. – Blastfurnace Jul 08 '19 at 16:36

1 Answers1

1

In the failure case, the current working directory is not what you are expecting.

You are loading the input file using a relative path, which fails to find the file, but you are not checking the return value of freopen() for error.

The variables you are reading into from cin are uninitialized, and you are not checking the result of operator>> for error before using the variables. They are being left unmodified on error. That is why you are getting random values on output.

You need to use an absolute path to the input file, not a relative path.

Since the input file is in the same directory as your executable, you can first retrieve the full path string to the executable (via the argv[0] parameter of main(), or via system calls like GetModuleFileName() on Windows), modify it to replace the 12.cpp.exe filename portion with input.txt, and then use that full path string to load the input file.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770