ifstream not working - c++

I'm trying to open a file using ifstream, but no matter what solutions I find that I've tried, nothing seems to work; my program always outputs "unable to open". Below is my code in its entirety. Any help at all is appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char ** argv)
{
string junk;
ifstream fin;
fin.open("somefile.txt");
if(fin.is_open())
{
fin >> junk;
cout << junk;
}
else
{
cout << "unable to open" << endl;
}
fin.close();
return 0;
}
Also, the contents of somefile.txt, which is in the same directory as the created executable is the following:
SOME
FILE

As some commenters have suggested, it could easily be that the file truly doesn't exist, because you're looking for it in the wrong place. Try using an absolute path to the file rather than just assuming it's looking where you expect.
And output a more helpful error message using strerror(errno).
// ...
fin.open("C:\\path\\to\\somefile.txt");
// ...
else
{
cout << "unable to open: " << strerror(errno) << endl;
}

Related

Trying to make something write to a file in c++

I tried programming a file writer, but when i try to write to a file with something that has multiple words it will suddenly create files.
My code
#include <fstream>
#include <iostream>
#include <unistd.h>
int main(int argc, char *argv[]) {
char cwd[256];
while (true) {
getcwd(cwd, 256);
std::string cwd_s = (std::string)cwd;
std::string Input;
std::cout << cwd_s << "> ";
std::cin >> Input;
std::ofstream file(Input);
std::cout << "cmd /";
std::cin >> Input;
file << Input;
};
for (int i; i < argc; i++) {
std::cout << argv[i] << '\n';
};
return 0;
}
I expected to get this:
C:\Users\code> File.txt
cmd /hello world!
File.txt
hello world!
But it only had "hello", it created another file named world!
I have tried changing the code, but to no avail.
So I have wrote this code that I think does what you expect. The behavior you were seing is because you used the same string to store the filename and the user input. Also you redefined a new file every loop (without closing the previous one). I added a signal handler since if you press Ctrl+C the program would quit without saving/closing the file.
I added comments about how you can make a better CLI interface (if you're interested)
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
std::ofstream outfile;
void signalHandler(int signum) {
outfile.close();
exit(signum);
}
int main() {
char cwd[256];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
std::cout << cwd << "> ";
} else {
std::cerr << "Error: Could not get current working directory." << std::endl;
return 1;
}
std::string filename;
std::getline(std::cin, filename);
outfile.open(filename);
// We intercept the Ctrl+C signal to close the file before exiting. Else nothing will be written to it.
// You can also use Ctrl+D (EOF: End Of File) to exit the program.
// The best praticte would be to implement a command line interface with a "quit" command. (like a map<string, function> for example)
signal(SIGINT, signalHandler);
// Another good practice is to check if the file did open correctly.
if (!outfile.is_open()) {
std::cerr << "Error: Could not open file for writing." << std::endl;
return 1;
}
std::cout << "cmd / ";
char ch;
while (std::cin.get(ch)) {
outfile.put(ch);
if (ch == '\n') {
std::cout << "cmd / ";
}
}
outfile.close();
return 0;
}
Hope it will help you ! And if you have any question about the code feel free to ask I'll explain !

How do you open a file using a string from an array?

I have an array of file names that I need to open. When I put in the plans.open. It gives me the error "no matching function for call to 'std::basic_ifstream::open(std::__cxx11:..."
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int main(){
ifstream files;
ifstream plans;
string stufiles[100];
int numFiles,timeBlocks;
files.open("filesToProcess.txt");
if (files.fail()){ //checks to see if the selected store file opened
cout << "Error when opening file!" << endl;
return 0;
}
files >> numFiles;
for (int i= 0; i<= numFiles; i++) {
files >> stufiles[i];
}
files.close();
cout << stufiles[0] << endl;
plans.open(stufiles[0]);
if (plans.fail()){ //checks to see if the selected store file opened
cout << "Error when opening file!" << endl;
return 0;
}
}
This is supposed to open the file using the file name in the array.
It gives me the error "no matching function for call to 'std::basic_ifstream::open(std::__cxx11:..."
Your compiler's version of std::ifstream::open() does not support std::string as input, so you will have to give it a const char* instead. You can use std::string::c_str() for that:
plans.open(stufiles[0].c_str());

Cannot open text file using ifstream

ifstream fin;
fin.open("‪C:\\Users\\Zach\\Desktop\\input.txt");
if (!fin)
{
cout << "e";
}
e is printing whether I use the full pathway or just input.txt from a resource file
If the file exists, make sure that you have got the path specified correctly. Since you're running on Windows, you can verify the full path to your executable with the following code.
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#define BUFSIZE 4096
std::string getExePath()
{
char result[BUFSIZE];
return std::string(result, GetModuleFileName(NULL, result, BUFSIZE));
}
int main()
{
std::ifstream infile("input.txt");
if (infile.is_open())
{
std::cout << "Success!" << std::endl;
infile.close();
}
else
{
std::cout << "Failed to open input.txt!" << std::endl;
std::cout << "Executable path is ->" << getExePath() << "<-" << std::endl;
}
return 0;
}
This will allow you to verify that your path to the input file is correct, assuming that it's collocated with your executable.
You need to direct output into the ifstream object by using fin << "string"; and not directing to standard out via cout.

when i open a file, nothing will be displayed - C++

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;
}

Trying to understand why the stream is failing while it's reading the whole file

I'm trying to read a whole text-file using a simple ifstream.
The code
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string line;
std::vector<std::string> DataArray;
//std::vector<std::string> QueryArray;
std::string filename = "c:\\helloworld.txt";
std::ifstream myfile(filename.c_str());
//std::ifstream qfile("queries.txt");
if (myfile.fail()) {
perror("c:\\helloworld.txt");
getchar();
return -1;
}
if (!myfile) //Always test the file open.
{
std::cout << "Error opening output file" << std::endl;
system("pause");
return -1;
}
while (std::getline(myfile, line))
{
DataArray.push_back(line);
}
/*if (!qfile) //Always test the file open.
{
std::cout << "Error opening output file" << std::endl;
system("pause");
return -1;
}
while (std::getline(qfile, line))
{
QueryArray.push_back(line);
}*/
//std::cout << QueryArray[20] << std::endl;
std::cout << DataArray[7] << std::endl;
return 0;
}
The result
I am getting the following result:
Error opening output file
The text-file my_text_file.txt is rightly in the same directory of my program.
Final question
It looks like it can't read my_text_file.txt, why? Did I do something wrong?
Also changing
std::ifstream myfile("c:\\my_text_file.txt");
to
std::ifstream myfile("my_text_file.txt");
doesn't solve the problem.
I think your error can be caused of many different reasons.
There is a handy Error-Message-Interpreteur thing called perror(c++ reference perror).
A standard way to use it(after declaring the file):
if(myFile.fail()){
perror("my_text_file.txt");
return -1;
}
That should give you a more detailed report on the issue, and it can tell you if the problem really is the directory of the file. Hope this helps.