Garbage values when writing and reading to a text file - c++

Can Some one help me the problem with this code? I am getting bunch of garbage value !
fstream fs("hello.txt");
if(fs.is_open())
{
string s = "hello";
string line;
fs << s;
while(getline(fs,line))
{
cout << line;
}
cin.get();
}
fs.close();
Thank you very much but when I try to do this I am getting same garbage. I am trying to rewrite the first hello with world and trying to print that line
fstream fs("hello.txt");
if(fs.is_open())
{
string s = "hello";
string line;
fs << s << endl;
fs.seekg(0);
fs << "world" << endl;
fs.seekg(0);
while(getline(fs,line))
{
cout<<line;
}
cin.get();
}
fs.close();

The cursor of fs is at the end of file after you fs << s (this is required to append data to the file properly).
Try to call fs.seekg(0); to move the cursor back to the beginning.
Also, you may need to supply the fstream::trunc or fstream::app flag when constructing fs.
fstream fs("hello.txt", fstream::in | fstream::out | fstream::trunc);

If hello.txt is empty prior to running the program then it seems to work for me. If the file contains more than 6 or 7 characters then your hello world code will overwrite the first 6/7 chars with "world" followed by the line terminator (which might be 1 or 2 chars depending on the platform). The reminder of the file won't be overwritten and will be subsequently printed by your getline loop.

Related

C++ line justification with I/O

I am creating a program that justifies a paragraph to ensure that each line has a length of 75 char. I have created functions that will insert spaces and create these desired lengths as needed, but I am having problems reading a text file and trying to break it down line by line. Each line provided is less than the 75 char limit, and my functions do properly work when it is given only a line. But I do not know how to read line by line, manipulate it, and then write to my new .txt file. When I output this to the new text file, I am greeted by a justified line of text, not text that is in a paragraph block!
I have tried to create an if else loop that would only run when the string.length() is less than 75 char, and would create a new line when false, but I do not know how to create this new line in the program
string myString;
string line("\n");
while (getline(inFile, myString))
{
cout << myString << endl;
puncLoop(myString);
spaceLoop(myString);
}
}
In Order to output the file with new line you can use "\n".
#include <iostream>
#include <string>
#include <fstream>
int main() {
//in file object
std::ifstream inFile("example.txt");
//out file object
std::ofstream outFile ("example2.txt", std::ios_base::out | std::ios_base::trunc );
//Checking if file exist
if( inFile && outFile )
{
//temp valarable to store each line
std::string mystring;
//Loop through each line
while (getline(inFile, mystring))
{
//... Call Your Business Logic functions here, ( make use of pass by refernce or return to get back the string )
outFile << mystring.c_str() << "\n";
}
//closing file after completing
inFile.close();
outFile.close();
}
else
{
std::cout << "Could not open File to read or write"<<std::endl;
}
return 0;
}

Error copying text from one file to another c++ fstream

This is my code
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream file;
file.open("text.txt", std::fstream::in | std::fstream::out |
std::fstream::app);
if(!file.is_open())
{
std::cout << "Could not open file(test.txt)" << std::endl;
} else {
file << "These are words \nThese words are meant to show up in the new file \n" <<
"This is a new Line \nWhen the new fstream is created, all of these lines should be read and it should all copy over";
std::string text;
file >> text;
std::cout << text << std::endl;
file.close();
std::fstream newFile;
newFile.open("text2.txt", std::fstream::in | std::fstream::out |
std::fstream::app);
if(newFile.is_open())
{
newFile << text;
}
}
}
I'm trying to copy the contents of text.txt to text2.txt but for some reason the text string always ends up empty. I've checked the files and text gets populated but text2 is empty. What's going wrong here?
When you append a string to an fstream, the input / output position is set to the end of the file. This means that when you next read from the file, all you will see is an empty string.
You can check what the current input position is by using:
file.tellg()
And set the input / output position to the start by using:
file.seekg(0)
The full reference for std::fstream is here.
You're trying to read from the end of the file. The position is set to the end of the last thing you wrote to the file, so, if you want to read what you wrote, you have to reset it:
file.seekg(0);
This will set the position for the input back to the start of the file. Note however that reading from the file the way you do now will simply get you 1 word (up to the first whitespace). If you want to read it all, perhaps you should look at something like: Read whole ASCII file into C++ std::string.

Why does rdbuf() not print anything?

In the following example,
ifstream myFile;
myFile.open("example.txt", ios::binary);
cout << myFile.rdbuf() << endl;
myFile.close();
The contents of the file will be printed, in its entirety on one line. You can also do it like this:
ifstream myFile;
myFile.open("example.txt", ios::binary);
unsigned char character = myFile.get();
while(myFile){
cout << "one character = ";
cout << character;
character = myFile.get(); //gets each individual character, 1 at a time
}
myFile.close();
And it will print the contents of the file, one character at a time. However, if you try to do the methods one after the other (in any order), only one method will actually print anything. Could someone explain why, in the following example, the call to rdbuf() won't print the contents of the file?
ifstream myFile;
myFile.open("example.txt", ios::binary);
unsigned char character = myFile.get();
while(myFile){
cout << "one character = ";
cout << character;
character = myFile.get(); //gets each individual character, 1 at a time
}
cout << myFile.rdbuf() << endl;
myFile.close();
Thank you!
As you read in from a stream, the read position is incremented. After reading in an entire file character by character, the read position is at the end of file. In this case, rdbuf() (the read buffer) has nothing further of interest.
If you wanted to print the file again using rdbuf() you can set the read position with myFile.seekg(0, std::ios::beg); prior to attempting to print. In this specific example an error bit may already be set, so you may need to do a myFile.clear() before moving the read pointer.

C++ Clears file when a new print action takes place

I have a C++ (Made in Netbeans 8 in Mac OS X 10.9) that in short writes to a file then ends the program. Here is the Meat of my program.
#include <iostream>
#include <fstream>
#include <sstream>
ofstream outfile("NETBEANS_PMCL.txt");
if(outfile.fail())
{
cout << "Cant open that file." << endl;
return 0;
}
outfile << "name" << endl;
outfile.close();
return 0;
But each time I run the program it rewrites on top of the name that was printed the last time I ran the program. How do I make it so that if there is content on the first line then skip two lines and print and if there is content there skip two lines and print and so on.
The problem is that ofstream is to write to a file, and what you want is to read to see if there is content, skeep 2 lines, and write new content.
std::fstream file("NETBEANS_PMCL.txt", std::fstream::in | std::fstream::out | std::fstream::app);
After that you may try to read 2 line and write content. Consider the function member getline to read the content.
getline (char* s, streamsize n, char delim );

Trouble reading from file using getline() c++

This code always prints the last line of the file. I expected it to print all the text, one line at a time, from the file. Any idea why it doesn't work?
string filename;
cout << "File to read: ";
cin >> filename;
ifstream afile;
afile.open(filename.c_str());
string line;
while(!afile.eof()) {
getline(afile, line);
cout << line;
}
afile.close();
Trying it this way does the same thing:
for (string line; getline(afile, line);) {
cout << line;
}
Maybe this is an issue with my terminal? This works...
for (string line; getline(afile, line);) {
cout << line << endl;
}
The problem is that only the last line is printed. Correct?
I suggest that you add std::endl in your while loop. It can make the issue more clear. Sometimes the output can be confusing.
You can also check the line-delimiting character in your input file. '\n' is the default delimiter for getline. If a different character is used, specify it as getline's 3rd parameter.
From cplusplus.com:
If the delimiter is found, it is extracted and discarded, i.e. it is
not stored and the next input operation will begin after it.
Since your original code snippet doesn't insert any extra newlines itself, there is nothing making the output to the terminal go to the next line. When the output runs out of horizontal space what happens next is up to the terminal. I'm not sure what terminal you're using but in your case, it just wraps the cursor back to the first character on that line without a linefeed. On a windows command shell, it just wraps around to the next line.
Also note that:
while(!afile.eof()) {
getline(afile, line);
cout << line;
}
is a common antipattern. As already pointed out, more appropriate would be:
while(getline(afile, line)) {
cout << line << '\n';
}
The file stream only becomes false after you've reached eof and try to read from it.