writing in a user-defined .txt file - c++

The basic syntax I use to write to a .txt file is this:
ofstream myfile;
myfile.open ("data.txt", ios::trunc);
outfile<<"writing";
Now, supposing i were to let the user decide which file should be accessed, could it be done through a string?
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ofstream myfile;
string filename;
char x;
cin>>x;
if (x==1)
filename="data2.txt";
myfile.open (filename, ios::trunc);
myfile<<"writing";
return 0;
}
I already tested this and it didn't work. My question is: is it possible to do such a thing? If yes, how? When i compile it, the error i get is the following:
undefined reference to 'std::basicofstream<char, std::char_traits<char> >::open(std::string const&, std::_Ios_Openmode)'
I can't understand what it is that's causing it.

Your error says it can't find open method that uses std::string.
Try this:
myfile.open(filename.c_str(), ios::trunc);
Some versions of C++ do not allow the std::string for open method, so you will have to use the c_str() method of std::string.

You should add an else branch since if x isn't equal to 1 open has nothing to open.
Also you forgot to declare ofstream myfile; in your second snippet. Maybe that's the reason this doesn't work (it shouldn't even compile).

Related

Creating a file with variable name in c++

so I want to create a file but the name of it will be dependent on the user input e.g. if the user types "shrek" the file must be named "shrek.txt". Thats what I came up with but it doesn't work.
int main(){
ofstream file;
string name = "abc";
file.open(name + ".txt");
file.close();
}
I guess you are using an old C++ standard. If that's the case, fstream::open won't accept a std::string, only a C string (char*). You can use c_str in your string to obtain a const char* that will be accepted:
int main(){
ofstream file;
string name = "abc";
string file_name = name + ".txt";
file.open(file_name.c_str()); // <- here
file.close();
}
However, it's recommendable to switch to a more modern standard, as your code actually works for C++11 and newer.
Do you have the libraries required? In this case #include fstream. Does the same issue happens to another complier? Check that out. I attempted this myself and your code surely works. Attempt to use my code which I confirm works and see if you have any issues.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string name;
cin>> name;
ofstream file(name +".txt");
file.close();
}

error no instance of overloaded function "getline" matches the argument list c++

error no instance of overloaded function "getline" matches the argument list
I cant seem to see what is wrong. I feel like I am passing the correct arguments (ie the std::ofstream and the std::string). Any help would be great thanks.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
ofstream yourFile;
myfile.open ("read.cc");
yourFile.open ("write.cpp");
string line;
This section in particular is the one that is getting an error.
if (myfile.is_open()){
The getline in the while loop is red and is giving me the overload error.
while(getline(myfile,line)){
yourFile << line <<"\n";
}
}
myfile.close();
yourFile.close();
return 0;
}
I thought I had set up the streams correctly.
An output stream is for writing to. For reading from, you want an input stream:
std::ifstream myFile;
// ^^

Opening a file in C++

I am trying to open a file stored on my c drive with name test.txt.I am getting a lot of errors.I am new to filing in C++.Please help me out thanks.
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream mystream;
mystream.open("C:\\test",ios::in||ios::out);
/*Check if the file is opened properly*/
return 0;
}
This
mystream.open("C:\\test",ios::in || ios::out);
should be
mystream.open("C:\\test",ios::in | ios::out);
You are using the logical OR operator (||) instead of the bitwise OR operator (|). The former returns a boolean value, while the latter returns the bitwise OR of the two values.
You probably also want to fully qualify the filename. For example:
mystream.open("C:\\test.txt", ios::in | ios::out);

Strange fstream problem

I have really strange problem. In Visual C++ express, I have very simple code, just:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?ยจ
EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.
Canonical code to write to a file:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file;
file.open("test.txt");
if ( ! file.is_open() ) {
cerr << "open error\n";
}
if ( ! ( file << "Hello" ) ) {
cerr << "write error\n";
}
file.close();
}
Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.
As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.
Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).
fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.
Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.
Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios_base::out);
if (not file.is_open())
{
// Your error-handling code here
}
file << "Hello";
file.close();
}
You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.
Theres two ways to fix this. Either do:
file.open("test.txt", ios::out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create an ofstream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}

ofstream error in c++

I am getting an ofstream error in C++, here is my code
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
error from Dev-C++ 10
C:\devp\main.cpp aggregate
`std::ofstream OutStream' has
incomplete type and cannot be defined
Thanks in advance
You can try this:
#include <fstream>
int main () {
std::ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
The file streams are actually defined in <fstream>.
You may not be including the appropiate header file.
adding #include <fstream> at the beggining of your source file should fix the error.
Probably, you are including the wrong header file. There is a header <iosfwd> that is used for header files that need to reference types from the STL without needing a full declaration of the type. You still are required to include the proper header <iostream> in order to use the types in question.
Include fstream header file that's it. Because ofstream & ifstream are included in fstream.
Add #include <fstream>.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
std::ofstream myfile;
myfile.open("example.txt", std::ios::out);
myfile << "Writing this to a file\n";
myfile.close();
return 0;
}
I faced the same error because I forgot to use using namespace std;
after including it, the problem was solved.