Read and Rewrite the same file in C++ - c++

I have to read from a file, do some operations based on the data I got from that file and then rewrite the whole file with new values obtained after the operations were made. I tried
fstream file("date.in", ios::in|ios::out)
but seems like it puts the new set of data at the end of file. Also tried
fstream file("date.in", ios::in|ios::out|ios::trunc)
but then I can't even read the first set of data as it appears not to be there.

If you want to read and write to the same offsets in the file, you can set the put and get pointers with seekp() and seekg(). Their documentation can be found at cppreference.com.

Related

How do I delete bytes from a file in C or C++?

I've been Googling this for hours...reading and reading and reading, and yet nothing I come across seems to answer this simple question: In C or C++ programming: I have a file, it contains "hello world". I want to delete "world" (like pressing Backspace in a text editor), then save the file. How do I do this?
I know that files are streams (excellent info on that here!), which don't seem to have a way to delete items from a file per say, and I've studied all of the file-related functions in stdio.h: http://www.cplusplus.com/reference/cstdio/fopen/.
It seems to me that files and streams therefore are NOT like arrays: I can't just delete a byte from a file! Rather (I guess?) I have to create an entire new file and copy the whole original file into the new file withOUT the parts I want to delete? Is that the case?
The only other option I can think of is to seek to the position before "world", then write binary zeros to the end of the file, thereby overwriting "world". The problem with this, however, is a text editor will now no longer properly display this file, as it has non-printable characters in it--and the file size hasn't shrunk--it still contains these bytes--it's just that they hold zeros now instead of ASCII text, so this doesn't seem to be right either.
Related
Resizing a file in C++
You want std::filesystem::resize_file()
Assume your original file is "data.txt". As part of your code, open a new temp file say "data.txt.tmp" and start writing contents to it from original file. Upon writing data, replace the original file with the new one.
You can use a memory map from the source file and copy the data blocks you want to another memory map over target file. That's the easy and fast way (see http://man7.org/linux/man-pages/man2/mmap.2.html)

Reading specific elements from a CSV file in C++

I'm trying to create a reference program which I think will use an excel spreadsheet to hold information for reading only. I want the user to be able to select a topic from an option list and have the information in the appropriate cell be fed back to them. The program is being written in C++. My question is, how do I access specific cells from a spreadsheet from my program? I've researched it a little and I've seen that I want to save my file as a csv and use fscanf to read the contents, but I'm at a loss as to how I would do this part. I googled it and found this thread:
http://www.daniweb.com/software-development/cpp/threads/204808/parsing-a-csv-file-separated-by-semicolons
but I think it reads in all of the data from the CSV? From what I can tell anyways. And I only want to pull specific elements. Is that possible?
If you only want specific elements, you would still have to parse all contents of the file until you reach those elements. You don't have to store values you don't need, but you do need to parse them to advance in the file.
Are you invoking the program from Excel? If you are, a little VBA goes a long way. You could always only export the cells of interest ready for your C++ program to read in.
Otherwise, other answers are correct. However, you don't need to load the entire file into memory at once. You can use std::fstream to open the file and read in each line of the file, parsing in the required information for each line.

Remove A Line Of Text With Filestreams (C++)

I have a large text file.
Each time my program runs, it needs to read in the first line, remove it, and put that data back into the bottom of the file.
Is there a way to accomplish this task without having to read in every part of the file?
It would be great to follow this example of pseudo code:
1. Open file stream for reading/writing
2. data = first line of file
3. remove first line from file <-- can I do this?
4. Close file stream
5. Open file stream for appending
6. write data to file
7. Close file stream
The reason I'm trying to avoid reading everything in is because the program runs at a specific time each day. I don't want the delay to be longer each time the file gets bigger.
All the solutions I've found require that the program process the whole file. If C++ filestreams are not able to accomplish this, I'm up for whatever alternative is quick and efficient for my C++ program to execute.
thanks.
The unfortunate truth is that no filesystem on a modern OS is designed to do this. The only way to remove something from the beginning of a file is to copy the contents to a new file, except for the first bit. There's simply no way to do precisely what you want to do.
But hopefully you can do a bit of redesign. Maybe each entry could be a record in a database -- then the reordering can be done very efficiently. Or perhaps the file could contain fixed-size records, and you could use a second file of indexes to specify record order, so that rearranging the file was just a matter of updating the indices.

Adding Data at beginning of file [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Delete a Line from a file in C Language
In C++, what is the proper way to insert a line at the beginning of a text file?
How can i add data at the beginning of a file using c/c++ programming?
I have tried following code :
fstream file;
stmt.open(L"d:\\xyz.txt",ios::in|ios::out|ios::app);
but this is appending at the end of file.
You cannot do that.
With only standard C or C++, if you want to do it atomically, you have to write everything to a new file (i.e. new data plus old file), and then move the file over. If you want to play it risky, you can read a block of data, and write the new content at the beginning and move the data up block by block (but if something interrupts you, you've destroyed the file).
If you have access to memory mapping, you can try a different approach: Memory-map the entire file, memmove it by the required offset, and memcpy the new data into the initial segment.
You could do this:
Create a new file
Add the new data at the top
Append the data from the old file
There's rename in cstdio but I'm sure there's also something C++-specific.
Your only options of opening a file as far as i know are read,write and append. Therefore you should read the entire file content (provided it's not a huge file), open a temp file for writing , then write what you want followed by the buffer you read from the old file.
You can also try to open the file in w+ mode and try to position the cursor at the beginning of the file but i don't know if that would work unfortunately

C++ cache file mean?

I got the C++ code as follows:
string cachefile = filename + ".cache";
ifstream cache(cachefile.c_str(), ios::binary);
As I did not find it in a C++ reference, what are these codes doing (like ifstream etc)? And what is the cache file please? Why should it be created? What are the advantages and how to interpret it? Above all, what is the function of the above codes?
See here for some information on ifstream, which is simply the class you can use to open a file just to read it.
There is no particular reference for ".cache" files, it all depends on the application you are working on.
ifstream is an input file stream that's part of the standard C++ iostreams library.
What the above code does is open a file in binary mode (ie, without any character translations) for reading.
Here's a tutorial for C++ file input/output.
A cache file is a file to store data for later use (usually to use again, and again.) A cache is used to help speed up your program. A cache isn't necessarily a C++ thing, just a software thing.
All the above code is open up a file (an ifstream) that could be used as a cache. You actually don't cache anything in the code you have.
Here's a description of ifstream: http://www.cplusplus.com/reference/iostream/ifstream/
The first line concatenates the string ".cache" to the end of the given file name. If filename contains "xyz.txt", then the cachefile name becomes "xyz.txt.cache".
The second line creates a binary input stream that reads from that cache file.
The cache file is used by the program to store data that now needs to be read. That much can be deduced from the names and context. We can't say much more than that; it depends on the entire application. There is no standard that I'm aware of for ".cache" files.
The easiest way to find out what a certain function or class does is to look at a reference website. My favorite for c++ is cplusplus.com. Here is a link to their entry on ifstream.
As far as cachefile goes, its a string and represents the filename for the filestream.
string cachefile = filename + ".cache";
This creates a new string, named cachefile, whose content is the content of filename, with ".cache" concatenated to it.
ifstream cache(cachefile.c_str(), ios::binary);
This opens an input file stream to binary read from a file with the name stored in cachefile.