write to a file
I want to write to开发者_Go百科 a file named "TEXT" and append to the file every time I run the program. It compiles but it does not take input. Please help out; I am new to programming.
Here's the code I'm working with:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main ()
{
string line;
ifstream file;
file.open("TEXT",ios::in |ios::app);
if (file.is_open())
{
while (file.good() )
{
getline (file,line);
cout << line << endl;
}
file.close();
} else
cout << "Unable to open file";
}
I am not sure what you want to do but here's some basic input/output operations on a text file. Hope it helps.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream input("TEXT", ios::in); // Opens "TEXT" for reading
if(input.fail())
{
cout << "Input error: could not open " << "TEXT" << endl;
exit(-1);
}
while(getline(input, line))
{
cout << line << endl; // prints contents of "TEXT"
}
input.close(); // close the file
ofstream output("TEXT", ios::app); // opens "TEXT" for writing
if(output.fail())
{
cout << "Output error: could not open " << "TEXT" << endl;
exit(-1);
}
output << "I am adding this line to TEXT" << endl; // write a line to text
output.close(); // close the file
return 0;
}
To write to the file rather than reading from it, you basically need to change the type of file
to an output stream (ofstream
), file
to cin
and cout
to file
. You can also simplify a few things. A stream will automatically convert to a true value if the next operation will succeed, and a false one if it will fail, so you can test a stream simply by referring to it. There's nothing wrong with (e.g.) while (file.good())
, it's just not as idiomatic as while (file)
.
#include <iostream>
#include <fstream>
#include <string>
#include <cerrno>
using namespace std;
int main () {
string line;
string fname="TEXT";
/* You can open a file when you declare an ofstream. The path
must be specified as a char* and not a string.[1]
*/
ofstream fout(fname.c_str(), ios::app);
// equivalent to "if (!fout.fail())"
if (fout) {
while (cin) {
getline(cin,line);
fout << line << endl;
}
fout.close();
} else {
/* Note: errno won't necessarily hold the file open failure cause
under some compilers [2], but there isn't a more standard way
of getting the reason for failure.
*/
cout << "Unable to open file \"" << fname << "\": " << strerror(errno);
}
}
References:
- Why don't the std::fstream classes take a std::string?
- Get std::fstream failure error messages and/or exceptions
This program successfully opens "TEXT" for reading and print its content to stdout...
If you want to read from input, you need to readline
from stdin
:
getline( cin, line );
instead of
getline (file,line);
Then you will need to open file
for writing (using ios::out
flag instead of ios::in
, and without ios::app
) and write in there instead than in stdout
:
file << line << endl;
instead of
cout << line << endl;
精彩评论