Newb here. I have spent the last 4 hours trying to solve this problem.
ifstream is suddenly not opening files.
ofstream has no problems writing to the file.
The file exists, it's contents are, ThisIsText, and it is in the reference directory, which I confirmed with system("dir & pause")
I tried Code::Blocks and Dev C++, but I think they're using the same compiler(GNU GCC Compiler).
I tried using the full filename path with double backslashes.
I see people mentioning permissions, but I don't know how to tinker with that.
I'm on Windows 10.
Edit: I just found a new compiler(Embarcadero 10.1 AKA Borland) and the code works with it. I still want to know what the problem is with GNU GCC
The following code skips to the else statement:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string message;
ifstream inputFile;
inputFile.open("File.txt");
if (inputFile.good())
{
inputFile >> message;
cout << message;
system("dir & pause");
}
else
{
cout << "failed to open input file\n";
system("dir & pause");
} return 0;
}
If it helps, I found the following code online and it outputs, "Error code = 2"
from winerror.h, that is: ERROR_FILE_NOT_FOUND
#include <windows.h>
#include <iostream>
int main()
{
HANDLE hFile = CreateFile(
"one.txt", // Windows does not case about case
GENERIC_READ,
0, // no sharing
NULL, // default security
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL ); // no file template
if(INVALID_HANDLE_VALUE == hFile)
{
DWORD errCode = GetLastError(); // see winerror.h for meanings
std::cout << "File wouldn't open :-(" << std::endl;
std::cout << "Error code = " << errCode << std::endl;
}
else
{
std::cout << "File opened OK :-)" << std::endl;
CloseHandle(hFile);
}
return 0;
}
PS. I know using namespace std; is bad practice
Related
I'm trying to open a file with a c++ program using ShellExecuteA in Windows10. (I'm also using VisualStudio2019 in case that's relevant.)
ShellExecute itself is working (I can use "explore" and "find" as it is intended), however it seems to be unable to find the file even though it exists in the directory. I have tried both an absolute as well as a relative path and neither work.
My code is this:
#include <iostream>
#include <windows.h>
#include <shellapi.h>
#include <string>
#include <limits.h>
using namespace std;
string getCurrentDir() {
char buff[MAX_PATH];
GetModuleFileName(NULL, buff, MAX_PATH);
string::size_type position = string(buff).find_last_of("\\/");
return string(buff).substr(0, position);
}
int main()
{
cout << "path: " << getCurrentDir() << endl;
int ret1 = (int)ShellExecuteA(NULL, "open", "C:\\Users\\Sasha\\source\\repos\\shellopen\\Debug\\MyTextFile.txt", NULL, NULL, SW_SHOWNORMAL);
cout << ret1 << endl;
int ret2 = (int)ShellExecuteA(NULL, "open", "MyTextFile.txt", NULL, NULL, SW_SHOWNORMAL);
cout << ret2 << endl;
return 0;
}
The result is
path: C:\Users\Sasha\source\repos\shellopen\Debug
2
2
"2" apparently means that the file couldn't be found, however "MyTextFile.txt" definitely exists in the directory and there is no spelling mistake.
I've tried googling the problem but it seems to be uncommon enough that I haven't found anything that works for me. I'd be very grateful for any help.
Ok, it turned out it was a spelling mistake, causing my file to be named "MyTextFile.txt.txt"
Thank you to everyone who tried to help me find the answer.
Premise: I'm using CLion.
As i said in title, when i try to open a file (txt) nothing will be displayed.
i can't explain it, i don't think i made an error, it's pretty easy this code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
FILE *leggi;
leggi = fopen("lorem.txt", "r");
char datiLetti[1000];
while(fgets(datiLetti, 1000, leggi)!=NULL){
cout << datiLetti << endl;
}
fclose(leggi);
system("PAUSE");
return EXIT_SUCCESS;
}
file "lorem.txt" is in the same directory of the project.
Thank you in advance.
EDIT1: file is lorem not lorem_ipsum, my mistake when i typed here.
You want this:
...
FILE *leggi;
leggi = fopen("lorem.txt", "r");
if (leggi == NULL)
{
cout << "Can't open file" << endl;
return 1;
}
...
---FIXED---
Installed cygwig1.dll and cygstdc++-6.dll and put cygwig in glob variables, then my file worked in the same directory of main and exe.
However, thank you guys for your time!
fopen is a C solution for open a file if you want to open a file in c++ use fstream like flowing code.
fopen is deprecated in c++11.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
fstream myfile;
myfile.open("example.txt");
cerr << "Error: " << strerror(errno);
if (myfile.is_open())
{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
I'm copypasting and then tinkering with various examples of PlaySound in order to figure out how to play a .wav file in a C++ program.
Right now I have one that appears to work more than any of the others, but when the file executes it doesn't play the .wav file and inside the window it tells me there is a File error with the .wav file.
To reiterate: the program builds and runs no problem. It is within the running program that the error appears. I can't quite figure out what the issue is. Could it simply be a location problem?
The error says: "Wave::file error: drake.wav"
I've set up SDL, though it's possible I've done that incorrectly. I used the guide on Lazyfoo. I'm using Codeblocks and MinGW.
Here's the code, which I found here:
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <mmsystem.h>
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
class Wave {
public:
Wave(char * filename);
~Wave();
void play(bool async=true);
bool isok();
private:
char * buffer;
bool ok;
HINSTANCE HInstance;
};
Wave::Wave(char * filename)
{
ok = false;
buffer = 0;
HInstance = GetModuleHandle(0);
ifstream infile(filename, ios::binary);
if (!infile)
{
std::cout << "Wave::file error: " << filename << std::endl;
return;
}
infile.seekg (0, ios::end);
int length = infile.tellg();
buffer = new char[length];
infile.seekg (0, ios::beg);
infile.read (buffer, length);
infile.close();
ok = true;
}
Wave::~Wave()
{
PlaySound(NULL, 0, 0);
delete [] buffer;
}
void Wave::play(bool async)
{
if (!ok)
return;
if (async)
PlaySound(buffer, HInstance, SND_MEMORY | SND_ASYNC);
else
PlaySound(buffer, HInstance, SND_MEMORY);
}
bool Wave::isok()
{
return ok;
}
int main(int argc, char *argv[]) {
std::cout << "Trying to play sound...\n";
Wave one("drake.wav");
one.play();
std::cout << "press key to exit";
getch();
return 0;
}
**EDIT: Thanks everyone for your help. It took me a while to figure this out.
Here's what I did:
1) I placed the .wav file inside the root folder.
2) I went to:
Project
Properties
Project's Build Options
Search Directories
Resource Compiler
and I placed the location of the file in the Resource Compiler.
**
There is a check in your code:
ifstream infile(filename, ios::binary);
if (!infile)
{
std::cout << "Wave::file error: " << filename << std::endl;
return;
}
So, it seems that the problem is simple: file not found. It means that this question is not about PlaySound, but about opening of a file.
You need to use full path (something like Wave one("c:\\project\\drake.wav");) or put wav-file right in the directory of the program (if you run the program from IDE, the current path of the program might be a little unexpected to you - not a path to executible file, but a path to a project file or something like this).
This question already has answers here:
Where to place file in order to read?
(4 answers)
Closed 6 years ago.
Why does my is_open() always fail and goes into the else statement which displays the error message?
Another method of mine is similar to this yet it worked.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string userName;
cout << "Please login to your account here!" << endl;
cout << "Username: ";
cin >> userName;
ifstream openSalt;
openSalt.open("salt.txt"); //open the file
if(openSalt.is_open()) //if file is open
{
string temp;
while (getline(openSalt,temp))
{
//gets content
//if user exists, login
//else, exit
}
openSalt.close();
}
else
{
cout << "Error opening file!" << endl;
exit(1);
}
return 0;
}
Assuming code is main function etc, the code works for me.
The issue is more likely to be that what ether tool/IDE you are using to compile the program sets the current folder to a different place to what you are expecting, and then is not the place the salt.txt file is in.
Check two things.
If the file really exists in the current folder from where you program is run ?
Do you have correct permissions to open the file ?
use this function to get the error :
std::string GetLastErrorAsString()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
if (errorMessageID == 0)
return std::string(); //No error message has been recorded
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
then call it in your else
else
{
cout << GetLastErrorAsString() << endl;
system("pause");
exit(1);
}
I used your code and it worked, make sure the file is in the same directory, make sure you are not working with a salt.txt.txt file (common mistake)
I realize that ofstream doesn't work on Windows 7 hidden file.
Here is the quick test code.
#include <fstream>
#include <iostream>
#include <tchar.h>
#include <windows.h>
int main() {
{
std::ifstream file2(_T("c:\\a.txt"));
if (file2.is_open()) {
std::cout << "ifstream open" << std::endl;
} else {
std::cout << "ifstream not open!" << std::endl;
}
}
// SetFileAttributes(_T("c:\\a.txt"), FILE_ATTRIBUTE_NORMAL);
SetFileAttributes(_T("c:\\a.txt"), FILE_ATTRIBUTE_HIDDEN);
{
std::ofstream file(_T("c:\\a.txt"));
if (file.is_open()) {
std::cout << "ofstream open" << std::endl;
} else {
std::cout << "ofstream not open!" << std::endl;
}
}
getchar();
}
Here is the output I am getting
ifstream open
ofstream not open!
If I am using FILE_ATTRIBUTE_NORMAL, ofstream will be opened successfully.
I do not run the program as Administrator. But, I do use the following linker option.
Having to turn No for Enable User Account Control (UAC) is important, if we do not start the application as Administrator. OS will help us to write the actual file to C:\Users\yccheok\AppData\Local\VirtualStore\a.txt instead of protected C:\
Does ofstream fail on Windows 7 hidden file, is an expected behaviour?
Yes. As noted in the underlying CreateFile documentation, " If CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if the file exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM attribute."
Or more readable: CreateFile fails if both CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, and if the file has the FILE_ATTRIBUTE_HIDDEN and/or FILE_ATTRIBUTE_SYSTEM attribute.
It just so happens that ofstream calls CreateFile like this.