C++ File I/O--can't read/write simultaneously? - c++

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

Related

Having an issue passing an array to a Function as only first word is printed c++

I am new to passing values to functions, please guide me what I am doing wrong here, thanks!
The question: Write a C++ program in which, read a c-string sentence
one by one from a file “sentence .txt”. Now your task is to break each
word of sentence into another c-string word, now write that word into
a file “word.txt”. Note : You must create atleast 1 function to
separate the words from sentence, you cannot use strings.
#include <iostream>
#include <fstream>
using namespace std;
char sentence2word(char array[100])
{
ofstream fout2;
fout2.open("word.txt");
fout2 << array << endl;
return array[100];
}
int main()
{
ifstream fin;
fin.open("sentence.txt");
char array[100];
fin >> array;
cout << "Output successful!";
sentence2word(array);
return 0;
system("pause");
}
The following program show how to get started with reading and writing from/into text files in C++. This is just to get you started and in practice i use std::string and std::istringstream to do this but in your note it is written that we cannot use strings so i did not use std::string. The program reads line by line from an input.txt file and write word by word into an output.txt file.
#include <iostream>
#include <fstream>//needed to read/write files
#define MAX_NUMBER_OF_CHARACTERS 500
using namespace std;
//function that writes lines word by word into output.txt
void writeWordByWord(std::ofstream &m_outFile, char (&lineArg)[MAX_NUMBER_OF_CHARACTERS])
{ int i = 0;
while(lineArg[i] != '\0')
{
if(lineArg[i] != ' ')
{m_outFile << lineArg[i];
//std::cout<< lineArg[i]<<" wrote"<<std::endl;
++i;
}
else{
m_outFile << '\n';
++i;
}
}
//m_outFile << '\n';
}
int main()
{
cout << "Hello World" << endl;
char line[MAX_NUMBER_OF_CHARACTERS];
std::ifstream inFile("input.txt");
std::ofstream outFile("output.txt");
while(inFile.getline(line, MAX_NUMBER_OF_CHARACTERS, '\n'))
{
std::cout<<line<<std::endl;
writeWordByWord(outFile, line);
}
inFile.close();
outFile.close();
return 0;
}

file.open not creating a new file in C++

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.

C++ copying another file

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

Delimit Sentences in C++, after each period

Sorry if I am brief I had a lot of trouble putting this code up here.
I want to basically parse the file "question.txt"
and every time I see a period i want a new line
basically:
hey jim.(new line)
hey tim.(newline)
int main(){
ifstream openQuiz;
openQuiz.open("questions.txt");
string line;
//int count = 0;
//Check for errors
if (openQuiz.fail()) {
cerr << "Error opening file" << endl;
}
//Reading from beginning to ending;
while (!openQuiz.eof()) {
}
openQuiz.close();
return 0;
}
You could use an fstream instead of an ifstream. The difference is that fstreams can do input and output at the same time.
Then you could simply read the characters one by one. Whenever you read a '.' write a newline.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream f("file.txt");
char c;
while (f.get(c)) {
cout << c;
if (c=='.') cout << endl;
}
return 0;
}
How's this for you?
You can read more about std::istream::get() here http://www.cplusplus.com/reference/istream/istream/get/

Can't get basic file input to work! (fstream)

Why won't my program open my .txt document? The document is at the specified location. And I know that \i is not an Escape Sequence.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream fin("C:\\input.txt");
if (!fin)
{
cerr << "Error, couldn't open txt file!" << endl;
return 1;
}
return 0;
}
You can alternatively use this code to input any file that is stored at C:\\text.txt into console window.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("D:\\text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout << output;
}
}
myReadFile.close();
return 0;
}
The document is at the specified location.
It's at C:\\input.txt? Really?
I'm pretty sure you intended:
fstream fin("C:\\input.txt");
That \\ is an escape sequence, resulting in a single backslash…
…and, ultimately, the path C:\input.txt.