I am writing a basic code but run into an error when trying to open a file. I've had a rough break and am having to start from the basics. Following is the part of the code where I run into the error:
int main()
{
string name;
fstream file;
cout << " Enter file name and type (E.g filname.txt) : ";
cin >> name;
file.open(name);
Following is the error:
[Error] no matching function for call to 'std::basic_fstream<char>::open(std::string&)'
I am returning after a long break so I apologize for any inconsistencies.
If the std::basic_fstream::open(std::string&) overload isn't available you are probably compiling using some C++ version prior to C++11.
Make sure you compile using at least C++11 and it should be fine.
you have to pass the open mode too.
Here is an example:
// print the content of a text file.
#include <iostream> // std::cout
#include <fstream> // std::ifstream
int main () {
std::ifstream ifs;
ifs.open ("test.txt", std::ifstream::in);
char c = ifs.get();
while (ifs.good()) {
std::cout << c;
c = ifs.get();
}
ifs.close();
return 0;
}
Code taken from Here
I suggest you to always check on cplusplus.com
It's very well documented!
Related
I am just trying to take a file name(example: file.txt) from user and reading it out. But getting some error. Can any body please help me out to perform this task successfully. If their is any other way of doing this please let me know. And please check your solution before answering.
ifstream myfile;
string myline, filename;
cin >> filename; // Reading the filename
myfile.open(filename);
if ( myfile.is_open() )
{
while ( myfile )
{
getline (myfile, myline);
cout << myline << " ";
}
}
for example I have a text file myfile.txt having content as
abc
def
fgh
So i will be getting the same thing as an output.
input: myfile.txt
output :
abc
def
fgh
If you have an old compiler then as commented by #πάνταῥεῖ .open() function may have no support for std::string filename, then you can use .open(filename.c_str()) to pass const char *. This correction is present in following code.
Also if you have older compiler, still you may solve your issue if you try to specify compiling option -std=c++11 to GCC/CLang compilers or /std:c++latest to MSVC compiler. This also may possibly solve your issue.
Otherwise update you compiler to new one.
As commented by #Someprogrammerdude instead of while (myfile) { getline(...); ... } you should use while (getline(...)) { ... }. This correction is also present in following code.
In following code I added first block in main() that writes to myfile.txt, this is only for testing example for StackOverflow visitors, so that example code is fully self-contained. You should remove this file-writing block, because you already have myfile.txt and this block will just overwrite it.
Full corrected code:
Try it online!
#include <iostream>
#include <fstream>
using namespace std;
int main() {
{
ofstream myfile("myfile.txt");
myfile << "abc\ndef\nfgh";
}
ifstream myfile;
string myline, filename;
cin >> filename; // Reading the filename
myfile.open(filename.c_str());
if ( myfile.is_open() )
{
while ( getline (myfile, myline) )
{
cout << myline << endl;
}
}
}
Output:
abc
def
fgh
I am trying to concatenate the contents of file1 and file2 into file3 using operator overloading in c++, but it is giving me 3 errors as mentioned
below :
Error : compiler could not generate operator= for class 'fstreambase'
Error : compiler could not generate operator= for class 'istream'
Error : compiler could not generate operator= for class 'ostream'
Here is my code :
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
class myfile
{
fstream file;
char filename[10],data[50];
public:
myfile()
{
//cout<<"File3 created\n";
}
myfile(char *fn)
{
strcpy(filename,fn);
}
void accept()
{
cout<<"\nEnter data for file "<<filename<<" :\n";
cin.getline(data,50);
file.open(filename,ios::out);
file<<data;
file.close();
}
void display()
{
char ch;
cout<<"Contents of "<<filename<<" :\n";
file.open(filename,ios::in);
while(file)
{
file.get(ch);
cout<<ch;
}
file.close();
cout<<endl;
}
myfile operator+(myfile &f2)
{
myfile f3("file3.txt");
fstream file1,file2,file3;
file1.open(this->filename,ios::in);
file2.open(f2.filename,ios::in);
file3.open(f3.filename,ios::out);
char ch;
while(file1)
{
file1.get(ch);
file3<<ch;
}
return f3;
}
};
void main()
{
clrscr();
myfile f1("file1.txt");
myfile f2("file2.txt");
myfile f3("file3.txt");
f1.accept();
f1.display();
f2.accept();
f2.display();
f3=f1+f2; //Those 3 errors generates on this line
f3.display();
getch();
}
Ps: The code is not yet complete(inside overloading function) and I'm using TurboC3 compiler
This is the question btw
What am I doing wrong here? Please help. Thank you.
You are over-engineering the problem. Modern C++, in particular, already makes copying file data around ridiculously easy.
To concatenate two files in memory:
Read the first file to a std::string
Read the second file to a std::string
Concatenate the strings
std::string read_file( const std::filesystem::path & filename )
{
std::ostringstream ss;
std::ifstream f( filename );
ss << f.rdbuf();
return ss.str();
}
std::string s = read_file(...) + read_file(...);
Steps 2 and 3 could be done at the same time
std::ostringstream ss;
std::ifstream f1(...);
std::ifstream f2(...);
ss << f1.rdbuf();
ss << f2.rdbuf();
std::string s = ss.str();
Write the string to the new file the usual way:
std::ofstream f3(...);
f3 << s;
To concatenate two files on disk:
std::ifstream f1(...);
std::ifstream f2(...);
std::ofstream f3(...);
f3 << f1.rdbuf() << f2.rdbuf();
Compilers
You really should have a modern C++ compiler working with C++17 at the bare minimum language standard.
However, if there is some reason you are constrained to an ancient, pre-standard C++ compiler, you can still use it. I never learned Borland’s pre-standard version of C++ file streams, so, alas, I cannot help much there. Read the documentation. It may not be possible to use the << operator to simply copy the stream buffer, but that is again just a read and write chars until EOF operation. You can make it into a little helper function taking both file objects by reference.
I'm doing a C++ intermediate course on udemy. At the lesson about reading text files the tutor has written the following code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string filename = "Text.txt";
ifstream inFile;
if (inFile.is_open()) {
string line;
while (!inFile) {
getline(inFile, line);
cout << line << '\n';
}
inFile.close();
}
else
cout << "Unable to open file";
return 0;
}
On the tutor's computer the program work fine but on my computer I get the error: error C3861: 'getline': identifier not found.
Even worse if I try (as my IDE -Visual Studio 2019- suggested) to replace getline by std::basic_istream::getline I get the error : 'std::basic_istream': use of class template requires template argument list. Does anyone understands what happens?
add header
#include<string>
as getline is part of this header file
and I will suggest you to always refer namespace
instead of
using namespace std;
use
std::cout
std::getline
etc
some strange behaviour occurred. So, i have program, which i just copypasted from cplusplus.com.
#include <iostream> // std::cin, std::cout
#include <fstream> // std::ifstream
int main () {
char str[256];
std::cout << "Enter the name of an existing text file: ";
std::cin.get (str,256); // get c-string
std::ifstream is(str); // open file
while (is.good()) // loop while extraction from file is possible
{
char c = is.get(); // get character from file
if (is.good())
std::cout << c;
}
is.close(); // close file
return 0;
}
In the same folder, where my program is, I have file named "hello.txt", which consist of 1 line "abc abc".
So, after I run program and input "hello.txt", I have following line:
hsdhs131313dhhsd
Which is, of course, not the content of "hello.txt". I am using mac os x and clang for compilation. Where is the problem, why code sample from official site not working? Thank you in advance
I am working on a small program that takes a input file and processors the data in the file. With my current code (see below) when you enter a valid file name it just freezes the command line (drops down a line and just shows a flashing _ ) and I have to kill the program to get out. If you enter a invalid file name the if(!file) gets called and runs fine.
Whats really odd is that if I put a debugging cout above that if statement it will not get called if the file name is correct. Hope you can help and if you need more info let me know!
This is my current code:
using namespace std;
#include <iostream>
#include <stdexcept>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include "Student.h"
int main(){
string filename, name;
char *inputfile;
ifstream file;
vector<Student> students;
const int SIZE = 200;
char buffer [SIZE];
int regno, i;
cout << "Enter file name: ";
cin >> filename;
inputfile = const_cast<char*> (filename.c_str());
file.open(inputfile);
if (!file){
cout << "Failed to open " << filename << endl;
exit(1);
}
while (!file.eof()){
file.getline(buffer, SIZE);
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
cout << regno;
}
file.close();
}
Your problems is that you never increase i in the cycle.
Here:
i = 0;
regno = 0;
while (isdigit(buffer[i])){
regno = (regno*10)+buffer[i];
}
You go into infinite cycle as i always stays 0.
Also why do you do the const_cast? You can open using a const char * too. So you can write this:
cin >> filename;
file.open(filename.c_str());
And code will still work.
There's another problem in your code concerning the use of getline() and eof(). The idiomatic way to read a file line-by-line is this:
std::string line;
while(getline(in, line)) {
// handle line here
}
in refers to some input stream like a std::ifstream or std::cin. The point is that reading a line can fail (e.g. due to EOF), which you check in above loop. Your version only checks if EOF was encountered before but not that the subsequent getline() call actually yielded any data.