ifstream read;
read.open(name);
char g[3];
read.getline(g,3);
char v = read.get();
cout << v;
read.close();
the issue i'm having is that after the getline function, the get is set to garbage and the file doesn't read properly anymore. However im sure that the file im reading contains more characters than getline takes, so what is issue?
Did you check that the read worked?
When you use a read always check the read worked before using the value:
if (read.getline(g,3)) {
// Read worked correctly
std::cout << "Got: >" << std::string(g, read.gcount()) << "<\n";
}
else {
std::cerr << "Read Failed\n";
throw "Failed";
}
if ((v = read.get()) != EOF) {
std::cout << "Got: >" << v << "<\n";
}
else {
std::cerr << "Read Failed\n";
throw "Failed";
}
Read file by std::fstream:
std::string str;
std::fstream file = "test.txt";//write in text.txt: GhY67. Test.
while(getline(file, str))//while get line of test.txt file,
// saves
// line in str string.
{
std::cout << str << '\n';
//Outputs str string(all lines in test.txt document)
}
If your wish always input characters, write this code:
std::string str;
while(getline(std::cin, str))//while getline in console, user
//inputs characters and characters in onr line saves in str
//string.*
{
if(str == "What?")
{
std::cout << "Hello, world!";
//*If user inputs string "What?", console outputs
string "Hello, world!*/
}
}
Related
I open the mp3 file by mistake with notepad++ ( Open with ) and show the entire file in text inside the notepad it was so cool.
since I am learning c++ again, I told myself let write a program that opens any file inside the console and display their content on the console so I begin my code like this :
int readAndWrite() {
string filename(R"(path\to\a\file)");
ifstream file(filename);
string line;
if (!file.is_open()) {
cerr << "Could not open the file - '"
<< filename << "'" << endl;
return EXIT_FAILURE;
}
while (getline(file, line)){
cout << line;
}
return EXIT_SUCCESS;
}
but it only shows 3 or 4 lines of the file and then exits the program I check my notepad++ again and find out about 700,000 line is in there.
I told myself maybe there is a character inside the file so I start writing the above code with the below changes. instead of displaying the file let's wrote inside a text file.
int readAndWrite() {
string filename(R"(path\to\a\file)");
string filename2(R"(path\to\a\file\copy)");
ifstream file(filename);
ofstream copy(filename2);
string line;
if (!file.is_open()) {
cerr << "Could not open the file - '"
<< filename << "'" << endl;
return EXIT_FAILURE;
}
while (getline(file, line)){
copy << line;
}
return EXIT_SUCCESS;
}
and again the same results. next try I give up on reading the file line by line so I start copying with this function.
void copyStringNewFile(ifstream& file, ofstream& copy)
{
copy << file.rdbuf();
}
and their results did not change a bit.
At this point, I told myself the problem is from file maybe and it is kinda is because when I use a simple text file all of the above codes work.
Like all other non-text files, mp3 files don't contain lines so you shouldn't use std::getline. Use istream::read and ostream::write. You can use istream::gcount to check how many characters that was actually read.
Since you are dealing with non-text files, also open the files in binary mode.
You should also test if opening both files works - that is, both the input and the output file.
Example:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
int readAndWrite() {
std::string filename(R"(path\to\a\file)");
std::string filename2(R"(path\to\a\file_copy)");
std::ifstream file(filename, std::ios::binary);
if(!file) {
std::cerr << '\'' << filename << "': " << std::strerror(errno) << '\n';
return EXIT_FAILURE;
}
std::ofstream copy(filename2, std::ios::binary);
if(!copy) {
std::cerr << '\'' << filename2 << "': " << std::strerror(errno) << '\n';
return EXIT_FAILURE;
}
char buf[1024];
while(file) {
file.read(buf, sizeof(buf));
// write as many characters as was read above
if(!copy.write(buf, file.gcount())) {
// write failed, perhaps filesystem is full?
std::cerr << '\'' << filename2 << "': " << std::strerror(errno) << '\n';
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
int main() {
return readAndWrite();
}
Not easy to formulate that question, so I am sorry for any grief there..
I am writing to a csv file like this at the moment:
double indicators::SMACurrentWrite() {
if ( !boost::filesystem::exists( "./CalculatedOutput/SMAcurrent.csv" ) ) // std::cout << "Can't find my file!" << std::endl;
{
std::ofstream SMAfile;
SMAfile.open("./CalculatedOutput/SMAcurrent.csv");
SMAfile << "SMA" << endl << SMA[0] << endl; // .. or with '\n' at the end.
SMAfile.close();
}
else {
std::ofstream SMAfile;
SMAfile.open ("./CalculatedOutput/SMAcurrent.csv", ios::app); // Append mode
SMAfile << SMA[0] << endl; // Writing data to file
SMAfile.close();
}
return 0;
}
Each time the application runs, a new value is appended to the output file at the end:
SMA
32.325
I guess there is no way of just squeezing that new vector entry in there under the header( and over the number), but that is what I want to accomplish anyway.
So I guess I would have to read the existing output file back in,put it in a vector, and then replace the old file ? I started with smth like this:
double indicators::SMACurrentWrite() {
if ( !boost::filesystem::exists( "./CalculatedOutput/SMAcurrent.csv" ) ) // std::cout << "Can't find my file!" << std::endl;
{
std::ofstream SMAfile;
SMAfile.open("./CalculatedOutput/SMAcurrent.csv", ios::app);
SMAfile << "SMA" << endl << SMA[0] << endl; // .. or with '\n' at the end.
SMAfile.close();
}
else {
std::ofstream SMARfile("./CalculatedOutput/SMAReplacecurrent.csv");
std::ifstream SMAfile("./CalculatedOutput/SMAcurrent.csv");
SMARfile << SMA[0] << endl; // Writing data to file
SMARfile << SMAfile.rdbuf();
SMAfile.close();
SMARfile.close();
std::remove("./CalculatedOutput/SMAcurrent.csv");
std::rename("./CalculatedOutput/SMAReplacecurrent.csv","./CalculatedOutput/SMAcurrent.csv");
}
return 0;
}
...., but of course that just puts the new data in above the header like this :
32.247
SMA
32.325
..rather than this
SMA
32.247
32.325
I would rather this didn't become such a time- consuming exercise, but I appreciate any help on how I could get this done.
If you read in the first line from the input file you can use that to start the new file and it will leave the file pointer at the second line where the old data starts. Then you can write the new stuff like this:
if(!boost::filesystem::exists("./CalculatedOutput/SMAcurrent.csv"))
{
std::ofstream SMAfile;
SMAfile.open("./CalculatedOutput/SMAcurrent.csv", ios::app);
SMAfile << "SMA" << '\n' << SMA[0] << '\n';
SMAfile.close();
}
else
{
std::ofstream SMARfile("./CalculatedOutput/SMAReplacecurrent.csv");
std::ifstream SMAfile("./CalculatedOutput/SMAcurrent.csv");
// first read header from input file
std::string header;
std::getline(SMAfile, header);
// Next write out the header followed by the new data
// then everything else
SMARfile << header << '\n'; // Writing header
SMARfile << SMA[0] << '\n'; // Write new data after header
SMARfile << SMAfile.rdbuf(); // Write rest of data
SMAfile.close();
SMARfile.close();
std::remove("./CalculatedOutput/SMAcurrent.csv");
std::rename("./CalculatedOutput/SMAReplacecurrent.csv",
"./CalculatedOutput/SMAcurrent.csv");
}
IN IOS app, module written in C++ I am writing my data (map of basic strings and integers) to a text file. Using following method:
bool Recognizer::saveMap(const char * s)
{
if(trainingData.model && !trainingData.model.empty()) {
const string filename = string(s);
std::ofstream file(s, ios_base::trunc );
try{
if(! file.is_open())
{
file.open(s);
}
for (map<String,int>::iterator it=trainingData.idMap.begin(); it!=trainingData.idMap.end(); ++it)
{
cout << it->second << " " << it->first << endl;
file << it->first << endl << it->second << endl;
}
file.close();
}
catch(cv::Exception & e){
if(file.is_open())
file.close();
int code = e.code;
string message = e.err;
cerr << "cv::Exeption code: " << code << " " << message << endl;
return false;
}
std::streampos fileLength = iosFileSize(s);
cout << "Saved map to: " << filename << " length: " << fileLength << endl;
return true;
}
return false;
}
My contains one entry and console output indicates that two lines: string, string representing number have been written to my file.
Subsequent opening file for reading and reading using getline or using stream operator indicates that file is empty:
bool Recognizer::loadMap(const char * s)
{
std::streampos fileLenght = iosFileSize(s);
std::ifstream file(s, ios::in);
try{
if(file.is_open())
{
string name;
string lineName;
string lineTag;
int tag;
int count = 0;
while(getline(file,name))
{
if(getline(file,lineTag))
{
tag = stoi(lineTag,0,10);
count++;
cout << tag << " " << name << endl;
trainingData.idMap[name]=tag;
trainingData.namesMap[tag]=name;
}
}trainingData.personsCount=count;
file.close();
}
}
catch(cv::Exception & e){
if(file.is_open())
file.close();
int code = e.code;
string message = e.err;
cerr << "cv::Exeption code: " << code << " " << message << endl;
return false;
}
cout << "Loaded map from: " << s << " lenght: "<< fileLenght << endl;
return true;
}
I also copied from one of stackoverflow answers method returning file lenght and using it to verify lenghth of the file after write operation:
std::streampos iosFileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}
The file path passed to saveMap and loadMap seems to be legit. With path that the app could not write to, attempt to write caused exception.
There are no errors returned by write operation but both, attempts to read and iosFileSize() indicate that file is empty.
I am not sure if i need call file.open() and file.close() or file is open and closed automatically when output stream is created and later goes out of scope.
I experimented with those with the same result ( call to file.is_open returns true so the block calling file.open() is skipped.
What am I doing wrong?
I appreciate all responses.
It does not seem like you call file.flush(); anywhere in Recognizer::saveMap() after writing to the file stream. std::ofstream::flush() saves changes you've made to the file. Add file.flush(); between when you make changes to the code and when you close the file. See if that remedies your issue.
I also had the same issue. Using file.flush() everytime after you insert to a file can save your file.
However if you insert something like this, say,
file << "Insert This"; You will need to add file.flush().
But some people have issues, like if you just insert file << "Insert This" << endl; , this works fine. The key point here is that, std::endl calls flush() everytime it is used internally. you can say it is a shortend form of "\n" + flush().
I believe from looking at your code that you are overwriting your data when you open the file in the second program you should be using something like this.
std::fstream fs;
fs.open ("test.txt", ios::app)
instead of doing the ios::in
Hello I'm writing a short program to implement a shell and I'm running into an unusual problem. For some reason I can't clear to the std::cout buffer. The program wont print out messages. I understand a simple solution is to switch to std::cerr, but is there a way to get messages to print with cout?
Things I've tryed:
std::cout.flush()
Inserting std::endl after anything is written to standard out.
Inserting an std::flush into the output stream
std::cout.setf(std::ios::unitbuf); which was something I found that should unbuffer output.
Any help is much appreciated here is my code:
int main()
{
//Tryed this to unbuffer cout, no luck.
std::cout.setf(std::ios::unitbuf);
std::string input;
//Print out shell prompt and read in input from keyboard.
std::cout << "myshell> ";
std::getline(std::cin, input);
//**********************************************************************
//Step 1) Read in string and parse into tokens.
//**********************************************************************
char * buf = new char[input.length() + 1];
strcpy(buf, input.c_str());
int index = 0;
char * command[256];
command[index] = std::strtok(buf, " "); //Get first token.
std::cout << command[index] << std::endl;
while (command[index] != NULL)
{
++index;
command[index] = std::strtok(NULL," "); //Get remaining tokens.
std::cout << command[index] << std::endl;
}
std::cout.flush(); //No luck here either
//HERE IS WHERE MY PROBLEM IS.
std::cout << index << " items were added to the command array" << std::endl;
delete[] buf;
return 0;
}
The problem is that you're sending NULL to cout on the last iteration of the while loop, which leads to UB, and in your case is jamming cout. Check for NULL before you send anything to cout and you're fine:
if (command[index] != NULL) {
std::cout << command[index] << std::endl;
}
If you ever need to know what happened to your streams, remember that they can carry status information (the iostate, which I recommend you read about). The following code could have helped track your error:
try {
std::cout.exceptions(std::cout.failbit);
} catch(const std::ios_base::failure& e) {
std::cerr << "stream error: " << e.what() << std::endl;
std::cout.clear();
}
// continue working with cout, because std::cout.clear() removed
// failbit
Or, even simpler:
if(not std::cout) {
// address your error (if it is recoverable)
}
This is how your code would have looked like:
#include <cstring>
#include <string>
#include <iostream>
int main()
{
//Tryed this to unbuffer cout, no luck.
std::cout.setf(std::ios::unitbuf);
std::string input;
//Print out shell prompt and read in input from keyboard.
std::cout << "myshell> ";
std::getline(std::cin, input);
//**********************************************************************
//Step 1) Read in string and parse into tokens.
//**********************************************************************
char * buf = new char[input.length() + 1];
strcpy(buf, input.c_str());
int index = 0;
char * command[256];
command[index] = std::strtok(buf, " "); //Get first token.
std::cout << command[index] << std::endl;
while (command[index] != NULL)
{
++index;
command[index] = std::strtok(NULL," "); //Get remaining tokens.
std::cout << command[index] << std::endl;
}
// I added from here...
if(not std::cout) {
std::cerr << "cout is messed up... fixing it..." << std::endl;
std::cout.clear();
}
// ... to here.
std::cout.flush(); //No luck here either
//HERE IS WHERE MY PROBLEM IS.
std::cout << index << " items were added to the command array" << std::endl;
delete[] buf;
return 0;
}
Result:
$ ./a.out
myshell> 1 2 3
1
2
3
cout is messed up... fixing it...
3 items were added to the command array
I've created a class which is supposed to read in DNA sequences: It contains an if stream private member:
Interface:
class Sequence_stream {
const char* FileName;
std::ifstream FileStream;
std::string FileFormat;
public:
Sequence_stream(const char* Filename, std::string Format);
NucleotideSequence get();
};
Implementation:
Sequence_stream::Sequence_stream(const char* Filename, std::string Format)
{
FileName = Filename;
FileStream.open(FileName);
FileFormat = Format;
std::cout << "Filestream is open: " << FileStream.is_open() << std::endl;
}
NucleotideSequence Sequence_stream::get()
{
if (FileStream.is_open())
{
char currentchar;
int basepos = 0;
std::string name;
std::vector<Nucleotide> sequence;
currentchar = FileStream.get();
if (currentchar == '>' && false == FileStream.eof()) { // Check that the start of the first line is the fasta head character.
currentchar = FileStream.get(); // Proceed to get the full name of the sequence. Get characters until the newline character.
while(currentchar != '\n' && false == FileStream.eof())
{
if (true == FileStream.eof()) {
std::cout << "The file ends before we have even finished reading in the name. Returning an empty NucleotideSequence" << std::endl;
return NucleotideSequence();
}
name.append(1, currentchar);
currentchar = FileStream.get();
} // done getting names, now let's get the sequence.
currentchar = FileStream.get();
while(currentchar != '>' && false == FileStream.eof())
{
if(currentchar != '\n'){
basepos++;
sequence.push_back(Nucleotide(currentchar, basepos));
}
currentchar = FileStream.get();
}
if(currentchar == '>')
{
FileStream.unget();
}
return NucleotideSequence(name, sequence);
} else {
std::cout << "The first line of the file was not a fasta format description line beginning with '>'. Are you sure the file is of FASTA format?" << std::endl;
return NucleotideSequence();
}
} else {
std::cout << "The filestream is not open..." << std::endl;
return NucleotideSequence();
}
}
However if I test it:
int main()
{
std::cout << "Let's try and read in a sequence!" << std::endl;
std::cout << "First we'll create a stream!" << std::endl;
Sequence_stream MyDNAStream("~/Dropbox/1_20dd5.fasta", "fasta");
std::cout << "Done!" << std::endl;
std::cout << "Now let's try and get a sequence!" << endl;
NucleotideSequence firstsequence = MyDNAStream.get();
return 0;
}
I see that the if stream is not open:
Let's try and read in a sequence!
First we'll create a stream!
Filestream is open: 0
Done!
The filestream is not open...
logout
[Process completed]
Although I thought the constructor function opens the if stream. What do I need to do to correct this so as the object is created and contains an open stream? (I know I'm yet to include a destructor which will close the stream upon destruction of the object).
Thanks,
Ben.
Your example shows that is_open returned false. I think you should check in your constructor that the file is indeed open, and throw if not.
In your case, I suspect this is due to passing "~/Dropbox/1_20dd5.fasta" as an input parameter. Did you test with a full pathname, with no ~? I have no knowledge of a C++ library that handles real path expansion (like python's os.path).