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;
}
}
Related
First, I am required to read in data from four input files. Second, I am required to create an array of structs and store the data into the structs. Thirdly, I must perform some manipulation on the data. Lastly, I am to print the manipulated data to an output file.
The first, I have never read in data from more than one file at a time. The second, I have never used a struct before, let alone an array of structs. I am stuck on the most effective method to read in the data from all four files and store that data into the array of structs.
Hence, my question to you is, what would be the best method for reading in the data?
I have been contemplating four different methods for a couple of hours now. Each one involves a while-loop with a “not end-of-file” Boolean expression.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char text[200]; // store data in an array
fstream file;
file.open ("example.txt", ios::out | ios::in ); // file name is exam for reading
// Reding from file
file >> text;
cout << text << endl; // print data of file thought array
//closing the file
file.close();
return 0;
}
Hope this will help you.
This question already has answers here:
How do I read an entire file into a std::string in C++?
(23 answers)
Closed 4 years ago.
I'm looking for a way to way to read files in C++ I can write files, but here's where I'm stuck at:
ifstream readfile;
readfile.open("C:/Users/Crazy/Desktop/Useless.txt")
I 've seen people do things such as:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout << output;
}
}
myReadFile.close();
return 0;
}
But in
char output[100];
I want the whole thing read.
Also, I just want to only read it, not to check if it's already open, not to, check for errors. I just want to read the whole thing, and the whole thing only.
If you want to read the entire file into a variable you'll need to:
1. Determine size of file in characters.
2. Use std::vector and declare a vector of that size,
or use the new operator and dynamically allocate a char array.
3. Use ifstream::read to read in the entire file.
4. Close the ifstream.
5. Remember to delete the char buffer.
I recommend using an OS API to determine the file length.
Edit 1: Example
#include <iostream>
#include <fstream>
#include <vector>
std::ifstream my_file("my_data");
my_file.seekg(0, std::ios_base::end); // Seek to end of file.
const unsigned int file_length = my_file.tellg();
my_file.seekg(0);
std::vector<char> file_data(file_length);
my_file.read(&file_data[0], file_length);
This question already has answers here:
How to truncate a file while it is open with fstream
(3 answers)
Closed 6 years ago.
Although I found a lot of stuff about std::fstream on SO, I still can't understand how it operates. Let's see this minimal example:
#include <fstream>
#include <string>
int main()
{
std::fstream fs{ "somefile.txt", std::fstream::out | std::fstream::in };
std::string line;
while (std::getline(fs, line))
{
// reads the whole file
}
// the purpose is to overwrite the whole file
fs.seekp(0, std::ios_base::beg); // moves at the beginning
fs << "Hello world!" << std::endl; // writes in the file
// possibly other read/write
}
This does not work, it seems that one cannot firstly read, and then write in the same stream according to everything I read about. I know the workaround that consists in closing the file, then opening it with the std::ios_base::trunc flag. However, that seems to be nonsensical: why is there such a limitation? Cannot we technically just overwrite the file after the reading?
The loop iterates until the fail bit gets set. Just clear() the flags prior to the seek:
fs.clear();
If you only want to overwrite the starting bit that is sufficient. If also want to truncate the stream I'd explicitly close() and open() it, where the open() would not set std::ios_base::in.
After reading the whole file, the fs is now in eof state. You need to clear the state so it can do following IO operations.
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 8 years ago.
In c++, how can I iterate through each line in a string? There have been plenty of questions regarding reading a file line by line, but how can I do this with a std::string?
For example, if I have the following string:
1051
2232
5152
3821
0021
3258
How would I iterate through each number?
In c++, you can use string exactly as files, using the classes defined in the sstream header:
#include <sstream>
//...
std::string str=...; // your string
std::istrstream in(str); // an istream, just like ifstream and cin
std::string line;
while(std::getline(in,line)){
//do stuff with line
}
This is a bit simplistic, but you get the idea.
You can use in just as you would use cin, e.g. in>>x etc. Hence the solutions from How do I iterate over cin line by line in C++? are relevant here too - you might want to look at them for the "real" answer (just replace cin with your own istream
Edit:
As a side note, you can create strings in the same way you print to the screen, using the ostream mechanism (like cout):
std::ostringstream out;
out << header << "_" << 3.5<<".txt";
std::string filename=out.str();
Use a tokenizer and let '\n' or '\r\n' or the appropriate newline for your OS be the token splitter..
Or if you were using a buffered file stream reader, just create a stringstream from this new string and read from the string stream instead of the file stream.
In short nothing changes except that you aren't reading from a file.
A horribly naive solution would be to make a string stream from this and assign ints or strings in a while loop from it.
I am writing a program in C++ which I need to save some .txt files to different locations as per the counter variable in program what should be the code? Please help
I know how to save file using full path
ofstream f;
f.open("c:\\user\\Desktop\\**data1**\\example.txt");
f.close();
I want "c:\user\Desktop\data*[CTR]*\filedata.txt"
But here the data1,data2,data3 .... and so on have to be accessed by me and create a textfile in each so what is the code?
Counter variable "ctr" is already evaluated in my program.
You could snprintf to create a custom string. An example is this:
char filepath[100];
snprintf(filepath, 100, "c:\\user\\Desktop\\data%d\\example.txt", datanum);
Then whatever you want to do with it:
ofstream f;
f.open(filepath);
f.close();
Note: snprintf limits the maximum number of characters that can be written on your buffer (filepath). This is very useful for when the arguments of *printf are strings (that is, using %s) to avoid buffer overflow. In the case of this example, where the argument is a number (%d), it is already known that it cannot have more than 10 characters and so the resulting string's length already has an upper bound and just making the filepath buffer big enough is sufficient. That is, in this special case, sprintf could be used instead of snprintf.
You can use the standard string streams, such as:
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
void f ( int data1 )
{
ostringstream path;
path << "c:\\user\\Desktop\\" << data1 << "\\example.txt";
ofstream file(path.str().c_str());
if (!file.is_open()) {
// handle error.
}
// write contents...
}