2

i try to open a file by class fstream in drive c: , but it does not work.

#include<fstream>

using namespace std;

int main(int argc, char* argv[]) {
        fstream f(L"c:/test.txt" , std::ios:out);
        if (!f)
        return 0;
    }

what is the problem in that code?

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • `fstream f(L"c://test.txt" , std::ios:out);` use two slash chars in path. –  Nov 20 '15 at 09:07
  • Doesn't the compiler give you an error, or at least a warning? There's no [`std::fstream` constructor](http://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream) which takes a wide-character string. – Some programmer dude Nov 20 '15 at 09:10
  • @dgate Not needed for forward-slash, only for backward-slash. – Some programmer dude Nov 20 '15 at 09:11
  • The only issue I see is that you are missing a `:` in `std::ios::out`. Other than that it worked for me. Could it be a permissions issue? Try running your IDE as 'admin'. – Mohamad Elghawi Nov 20 '15 at 09:13
  • @Joachim Pileborg Ohh yes you are correct. Its two backward slash to be used in windows as a file separator. –  Nov 20 '15 at 09:16
  • @JoachimPileborg There is in the Visual C++ implementation. – Mohamad Elghawi Nov 20 '15 at 09:18
  • / works like \\ in path of a file . i think access to drive c directly is impossible. –  Nov 20 '15 at 09:25

2 Answers2

1

It is most likely because your application does not have the correct permissions to open that file.

Solution.

Try running your application/IDE as admin by right-clicking on it and selecting the "Run as administrator" option.

Notes.

It is not a common use case of most applications to write directly into C: drive and there is no trivial method around this. You either start your application with the correct permissions or you move your file elsewhere.

If you absolutely must do this then you can start your application as admin, read/modify your file(s) and then drop your application's privileges.

Community
  • 1
  • 1
Mohamad Elghawi
  • 2,071
  • 10
  • 14
0

try this:

fstream f("c:\\test.txt" , std::ios:out);

need double \\