Difference in use and efficiency when using ifstream [duplicate] - c++

This question already has answers here:
The difference between using fstream constructor and open function
(4 answers)
Why do C++ standard file streams not follow RAII conventions more closely?
(5 answers)
Closed 1 year ago.
I am currently writing a program to read data from a big .csv file and wanted to know if there's any difference between using:
ifstream handle("filename");
and
ifstream handle;
archivo.open("filename", ios::in);
when opening the file.
I have tried both so far and the two have worked in reading the data to then store it in an STL container. I wanted to know if there's any concrete difference in use, efficiency and/or memory use.
Thanks in advance!

There is no differences between them.
ifstream handle("filename"); - you make ifstream type variable and then you open a file in one part of code;
ifstream handle; - you make ifstream type variable;
handle.open("filename", ios::in); - you open file in another part of code.
Second version can be useful when you need to have an ifsteam like a member of a class.
For example:
class myClass
{
public:
myClass(std::string str)
{
file.open(str);
}
private:
ifstream file;
...
};

Related

C++ read from file only when there is more content [duplicate]

This question already has an answer here:
Read data from fstream
(1 answer)
Closed 3 years ago.
How can I check if there is more content in a text file in c++ and if there is continue to read it?
I am trying to read a some words from a text file but the number of words is not specified.
Check out this link here.
Also, std:: is a reference to the namespace of code you are calling. When you include a file that is in the standard libraries, such as string, vector, fstream, iostream, you need to either declare that your file will use the namespace std with using namespace std; OR you append std:: to the method or variable.
Use std::vector and std::string. Use a correct form of reading a file:
std::string word;
std::vector<std::string> word_database;
while (text_file >> word)
{
word_database.push_back(word);
}
std::cout << "Words read: " << word_database.size() << "\n";

MoveFileA() doesn't like my arguments [duplicate]

This question already has answers here:
How to convert std::string to LPCSTR?
(9 answers)
Closed 8 years ago.
I have a list of file names in a .txt document, and I would like to move each of these files from one folder to another.
Using MoveFileA() I am getting the error, "no suitable conversion between std::string and LCPSTR".
Here is my code, after opening up my .txt file:
while (std::getline(myfile, line))
{
std::string oldLocation = "C:\\Users\\name\\Desktop\\docs\\folder1\\" + line;
std::string newLocation = "C:\\Users\\name\\Desktop\\docs\\folder2\\" + line;
MoveFileA(oldLocation, newLocation);
}
If I type in the full path as arguments for MoveFileA, instead of sending it a variable, it works but I am unable to iterate over .txt file this way.
Any suggestions on how I might fix this?
LCPSTR means long constant pointer to a string, which means it's a null terminated c string.
std::string is an object. It is something different. But it luckily provides a convenience method c_str the provides a pointer to a constant c style string. So as the comment says you should go by:
MoveFileA(oldLocation.c_str(), newLocation.c_str());
It is worth of explicitly noting, that you can't drop it in every place instead of char*, but only when the string won't be modified. It returns const char*. This is where the C in LCPSTR gets important.

reading from ifstream file gives wrong size [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 8 years ago.
I have a .txt file containing 6291456 numbers and nothing else. After reading all out and push_back into a vector, the vector.size() function returns 6291457. Where does this additional element come from?
int disparity;
ifstream disparity_txt;
disparity_txt.open(path);
while(!disparity_txt.eof())
{
disparity_txt >> disparity;
vec_disparities.push_back(disparity);
}
cout << vec_disparities.size() << endl;
disparity_txt.close();
Don't use while(!disparity_txt.eof()) it does not do what you think (eof will only be set after the end of the stream is read, so typically the last iteration is wrong) :
Do :
while(disparity_txt >> disparity)
{
vec_disparities.push_back(disparity);
}
Using while (!in.eof()) is almost always wrong
Either stop looping when extracting a number from the stream fails (as shown in quantdev's answer) or use the standard library facilities meant for populating a container from a stream:
std::ifstream disparity_txt(path);
vec_disparities.assign(std::istream_iterator<int>(disparity_txt),
std::istream_iterator<int>());
You can open an fstream using its constructor, and the destructor will close it, you don't need explicit open and close calls.
In C++11 it's even simpler:
vec_disparities.assign(std::istream_iterator<int>{std::ifstream{path}}, {});

How to read a file in reverse order using C++ [duplicate]

This question already has answers here:
Read a file backwards?
(7 answers)
Closed 8 years ago.
How can I read a text file in reverse order (i.e. from eof) using C++?
Yes, but you basically have to do it manually.
The basic algorithm is as follows:
Seek to the end of the file with is.seekg(0, is.end)
Determine the file size with is.tellg()
Repeatedly seek backwards and read chunks of the file until you reach the front
If the file is small enough so the entire contents easily fit within memory, it will be both far faster and far easier to code to read the file forward into a string and then reversing that string after the fact.
If the contents won't fit in memory, you'll have to use nneonneo's solution. It would probably be best to turn off buffering.
Just use the seekg and related functions in istream class. Here is a working example. Tested.
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream in("file.txt");
// Get the length of the file
in.seekg(0, in.end);
int len = in.tellg();
// Start reading the file in reverse
char c;
while (len--)
{
in.seekg(len, in.beg);
in >> c;
cout << c;
}
}

Which is the best way to read binary file content to std::string? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to use istream with strings
std::ifstream ifile(absolute_file_path.c_str(),std::ios::binary | std::ios::in | std::ios::ate);
if (ifile.is_open()==false)
{
throw std::runtime_error("Unable open the file.");
}
std::stirng file_content;
//here I need good way to read full file to file_content
//note: the file is binary
ifile.close();
This are ways I know:
1.Maybe not safe
file_content.resize(ifile.tellg());
ifile.seekg(0,std::ios::beg);
if(!ifile.read(const_cast<char *>(file_content.data()), file_content.size()));
{
throw std::runtime_errro("failed to read file:");
}
ifile.close();
2.Slow
file_content.reserve(ifile.tellg());
ifile.seekg(0,std::ios::beg);
while(ifile)
{
file_content += (char)(ifile.get());
}
If the file is binary, it might contain '\0' which is a weird character to be contained in an std::string. Although I think you could do that, you will be asking for problems because some operations on a std::string take a const char* which is null-terminated. Instead, go with std::vector<char>, a much safer way.
If you go with strings anyway, just do a loop calling std::string::append(size_t, char).
while(!ifile.eof()) {
contents.append(1, ifile.get());
}
EDIT: I think you can also do something in the lines of:
std::string contents(std::istreambuf_iterator<char>(ifile), std::istreambuf_iterator<char>());
You should be clear with binary file and string. Do you mean to read the content of that file, or you want to read binary representation of the file to string? Normally an unsigned char[] buffer is used to store content of binary files. And string is used to store content of a text file.