简体   繁体   中英

Fail to create a .txt file and write to it in C++?

Inside one of my functions that are being called by the main() , I have the following very simple testing snippet.

ofstream outFile;
outFile.open("C:\\Program Files\\data\\test.txt");
outFile << "test\n";
outFile.close();

After running the code, I didn't see the file appears. Why is it so?

Unfortunately C++ does not specify any way to get more detailed error. See Get std::fstream failure error messages and/or exceptions .

But the platform-specific interface should work. After each operation check whether outFile.bad() and if it is true, check GetLastError() . Interpret according to appropriate table in documentation or using FormatMessage .


I would suspect the problem is permissions. Windows Vista introduced this "user access control" that should pop up a dialog whenever program wants to do something that requires administrator privileges even if the current user has them. The problem is that the dialog only pops up under certain conditions. Notably it will not pop up for console applications and the application is denied permissions right away. Such application has to be explicitly executed "as administrator". Of course don't forget being able to write particular file there does not imply being able to create a new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM