I am trying to run below code but it is neither showing any file on the path nor reading anything from it. Whatever I am writing into the file through "cin >>" it is not being written. Can anybody please let me know mistake in my code below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char string[80];
cout << "Enter Input" << endl;
cin >> string;
int len = strlen(string);
fstream file;
file.open("TEXT", ios::in | ios::out);
for (int i = 0; i < len; i++)
file.put(string[i]);
file.close();
file.open("TEXT", ios::in | ios::out);
file.seekg(0);
cout << "Output" << endl;
while (file) {
char ch;
file.get(ch);
cout << ch;
}
file.close();
return 0;
}
You should add the fstream::app flag in your open call and this will do the trick !
Don't mess with file modes you don't need (or understand). Open the file for writing only first, and then open it for reading only next. Use different streams for reading and writing.
ofstream file_out;
file_out.open("TEXT");
for (int i = 0; i < len; i++)
file_out.put(string[i]);
file_out.close();
ifstream file_in;
file_in.open("TEXT");
cout << "Output" << endl;
while (file_in) {
char ch;
file_in.get(ch);
cout << ch;
}
Unless you actually understand the rules concerning ios::in and ios::out it's safer to just use ifstream when you want input and ofstream when you want output.
More reading if you do want to understand the rules.
Related
I'm learning file handling in C++. I was implementing the exact same code in my Code::Blocks 20.03 as given in one of the programs of the book, but it's displaying no output after line 26, i.e.
cout<<"\nReading the file contents: ";
I've figured maybe these lines are erraneous, but I can't debug how:
while(file){
file.get(ch);
cout<<ch;
}
Here is the full code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int main()
{
char String[80];
cout<<"Enter a string: ";
cin>>String;
int len = strlen(String);
fstream file;
cout<<"Opening the 'TEXT' file and storing the string in it.\n\n";
file.open("TEXT",ios::in|ios::out);
for(int i=0;i<len;i++)
file.put(String[i]);
file.seekg(0);
char ch;
cout<<"\nReading the file contents: ";
while(file){
file.get(ch);
cout<<ch;
}
file.close();
return 0;
}
The openmode
ios::in | ios::out
will not create a new file if "TEXT" does not exist, but result in an error. Most likely this file does not exist, so you get an error and any subsequent input and output operations on the stream are ignored. You could use
ios::in | ios::out | ios::trunc
to destroy the contents of an existing file or create a new one if the file does not exist.
For further information please consult the table on https://en.cppreference.com/w/cpp/io/basic_filebuf/open where all the different combinations of openmode are detailed.
Lastly, it's always good practice to check if the file was opened:
if(!file) { /* error */ }
You can use is_open() to check if the file was successfully opened and then use an if else loop that will validate if the file can't be found. You don't need to use ios::in|ios::out.
Here's an example that should work:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream filestr;
filestr.open ("test.txt");
if (filestr.is_open())
{
filestr << "File successfully open";
filestr.close();
}
else
{
cout << "Error opening file";
}
return 0;
}
You need to check for end of file inside the loop.
while(file) {
file.get(ch);
if(ch == -1) break;
cout << ch;
}
Also, try opening the file in write mode first and then close it and open it in read mode.
cout << "Opening the 'TEXT' file and storing the string in it.\n\n";
ofstream outfile("TEXT");
if(outfile.is_open()) {
for(int i = 0; i < len; i++)
outfile.put(String[i]);
outfile.close();
}
ifstream infile("TEXT");
char ch;
if(infile.is_open()) {
cout << "\nReading the file contents: ";
while(infile) {
file.get(ch);
if(ch == -1) break;
cout << ch;
}
infile.close();
}
My FILE WONT OPEN HELP
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string input_file_name, output_file_name; //file names
ifstream infile; //input file object
ofstream outfile; //output file object
//prompt user for input file
cout << "Enter the input file name: ";
cin >> input_file_name;
//open input file
infile.open(input_file_name.c_str());
//check if file opened successfully
if (!infile)
{
cout << "Error: Unable to open file" << endl;
cout << "Terminating program...";
return 1;
}
else
{
cout << "Successfully opened file!";
}
return 0;
}
when asked for user input i type filename.txt and it wont display successfuly opened message? why....i have the filename.txt on my pc
First off, pardon my use of 'goto', I just felt like it... Try something like what I have shown below where I check if the file actually opened (save the code stub as "asdf.cpp"). Of course you will have to read the data into an array, but it may be a good place to start.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
string line;
ifstream f("asdf.cpp");
if ( !f.is_open() )
goto error_file_not_open;
while( getline(f, line) )
cout << line << endl;
f.close();
return 0;
error_file_not_open:
cout << "Could not open file" << endl;
return -1;
}
If you want to save and read values from/to file, then try something like this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
// Write values to a file
const int size = 5;
int values[] = { 1,2,3,4,5,6 };
ofstream myfile("lol.txt");
if (myfile.is_open())
{
for (int count = 0; count < size; count++) {
myfile << values[count] << endl;
}
myfile.close();
}
else {
cout << "Unable to open file";
}
// Write read values from a file
std::ifstream file("lol.txt");
if (file.is_open()) {
std::string line;
while (getline(file, line)) {
cout << line.c_str() << endl;
}
file.close();
}
else {
cout << "Unable to open file";
}
}
I'am afraid that your file is not an ANSI-ASCII encoded text file. May be it is encoded by UTF-8 or the Unicode format. The following code will check that the encode of your file. Just try to run it or you could open the lol.txt by any text editor such as, vscode or notepad++.
It will show the encode format of the file at the right-down corner.
Another way to prevent from this issue is try to save the text file to the ANSC-ASCII format. Hope this will help! ^_^
#include <iostream>
#include <fstream>
using namespace std;
unsigned char UTF8Header[] = {0xef, 0xbb, 0xbf};
unsigned char UNICODEHeader[] = {0xff, 0xfe};
int main()
{
char fileName[] = "lol.txt"; // replace the file with your actual file name.
std::ifstream in;
char buffer[3] = {0};
in.open(fileName, std::ios::in | std::ios::binary);
if (!in.is_open())
{
std::cout << "Error opening file";
return -1;
}
if (!in.eof())
in.read(buffer, 2);
if (!in.eof())
in.read(buffer + 2, 1);
if (buffer[0] == UNICODEHeader[0] && buffer[1] == UNICODEHeader[1])
cout << "The file is encoded by unicode format" << endl;
else if (buffer[0] == UTF8Header[0] && buffer[1] == UTF8Header[1] && buffer[2] == UTF8Header[2])
cout << "The file is encoded by UTF-8 format" << endl;
return 0;
}
I'm studying C++ and I don't know how to read blank word(like " ")
my code just reading only "words"
please help me
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[]) {
ofstream output("data4.dat", ios::out | ios::binary);
string buffer = "A program that translates a high level languageto a machine language\n is called a compiler. A compiler is thus a somewhat peculiar sort\n of program and its output is yet another program. To avoid confusion,\n the input program is usually called the source program or\n source code, and the translated version produced by the compiler is called";
output << buffer;
output.close();
ifstream is;
ifstream input("data4.dat", ios::in | ios::binary);
string in_buffer;
if (! is.eof()) {
for ( int i = 0; i < sizeof(input); i++) {
input >> buffer[i];
}
}
input.close();
std::cout << buffer[2] << '\n';
return 0;
}
i was wondering how to use c++ ifstream/ofstream to copy a file and save it as another name.
this is as far as i got. I know how to get the file, its just that i don't know how to copy that file and save it as a different name.
#include<iostream>
#include<fstream>
#include<string>
namespace std;
int main()
{
ofstream
ifstream
cout << "enter your file you want to copy"<< endl;
cin >> input_file_name;
in_file.open(input_file_name);
if (!in_file)
{
cout <<" there is no such file"<<endl;
return 0;
}
cout <<" enter the name you want to save this copy file"<<endl;
cin >> output_file_name;
out_file.open(output_file_name);
if (!out.file)
{
cout<<"file is not available"<<endl;
return 0;
}
in_file.close();
out_file.close();
return 0;
}
rdbuf with overloaded << is standard way to go.
ifstream src;
ofstream dst;
src.open("from", ios::in | ios::binary);
dst.open("toto", ios::out | ios::binary);
dst << src.rdbuf();
src.close();
dst.close();
Copy a file and save it on another file:
#include <fstream>
#include <iostream>
#include <string>
int main(int arc, char* argv[]) {
std::ifstream file1(argv[1]);
std::ofstream file2(argv[2]);
std::string line;
if (file1.good() && file2.good()) {
while (getline(file1, line)) {
file2 << line;
file2 << '\n';
}
}
file1.close();
file2.close();
}
Basically you want to read a character at a time and write said character to the output stream. There's a get() overload which accepts a streambuf output variable that would work. You could also use the example on cplusplus.com rdbuf documentation.
http://www.cplusplus.com/reference/fstream/ofstream/rdbuf/
This code below should give you a sense of what you want to do.
There are few things you should keep in mind, for example:
is the path of the file giving to read is valid?
or do you want to save the data from an output file if that file exists, before pushing new data?.
You could test this code by just creating a file into your desktop or any location, just change the filePath and destinationPath variables then run the code. (c++ 11)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<string> readFromFile(const char *filePath) {
vector<string> container;
ifstream obj(filePath); // automatically our file would be open
if (obj.is_open()) { // we check anyways
string line = "";
while(getline(obj, line)) {
if (!line.empty()) // prevent us to insert empty line into our vector
container.push_back(line);
}
obj.close(); // close after we finish reading to avoid corruption
}
return container;
}
bool pipingToDestination(vector<string>data, const char *filePath) {
std::filebuf fb; fb.open(filePath,std::ios::out); // open the file
ostream obj(&fb);
if (!data.empty() && fb.is_open()) { // make sure we have some data && the file file is open to write
for (string x: data) { // c++11
obj << x << endl;
}
fb.close();
return true;
}
return false;
}
int main() {
string filePath = "/Users/lamar/Desktop/testFile.txt";
vector<string> data = readFromFile(filePath.c_str());
cout << "File has passed data into container ... \n";
for(string x: data) {
cout << x << endl;
}
cout << "Creating destination file \n";
string destinationPath = "/Users/lamar/Desktop/destFile.txt";
cout << "has piped data into file " << boolalpha << pipingToDestination(data, destinationPath.c_str());
return 0;
}
This is not the only way to do this, but this code should put you on a direction
I'm writing some simple code that's supposed to read every other character, as well as overwriting their adjacent characters with '?'s in a random text file.
eg.
test.txt contains "Hello World";
after running the program, it'd be "H?l?o?W?r?d"
My code below allows me to read every other character from the text file in the console window, but after the program ends and when I open up test.txt, nothing has been changed. Need help to figure out why...
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (!data.eof())
{
if (!data.eof())
{
char ch;
data.get(ch);
cout << "ch is now " << ch << endl;
}
if (!data.eof())
data.put('?');
}
data.close();
return 0;
}
You forgot to consider that you have 2 streams, istream and ostream.
You need to synchronize the location of these 2 streams to achieve what you want. I modified your code a bit to show what I mean.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char ch;
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (data.get(ch))
{
cout << "ch is now " << ch << endl;
data.seekg(data.tellp()); //set ostream to point to the new location that istream set
data.put('?');
data.seekp(data.tellg()); //set istream to point to the new location that ostream set
}
data.close(); // not required, as it's part of `fstream::~fstream()`
return 0; // not required, as 0 is returned by default
}
You are misusing eof(). Do it like this instead:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
char ch;
while (data.get(ch))
{
cout << "ch is now " << ch << endl;
data.put('?');
}
data.close();
return 0;
}