Partially truncating a stream (fstream or ofstream) in C++ - c++

I am trying to partially truncate (or shorten) an existing file, using fstream. I have tried writing an EOF character, but this seems to do nothing.
Any help would be appreciated...

I don't think you can. There are many functions for moving "up and down" the wrapper hierarchy for HANDLE<->int<->FILE *, at least on Windows, but there is no "proper" to extract the FILE * from an iostreams object (if indeed it is even implemented with one).
You may find this question to be of assistance.
Personally I would strongly recommend steering clear of iostreams, they're poorly designed, heavily C++, and nasty to look at. Take a look at Boost's iostreams, or wrap stdio.h if you need to use classes.
The relevant function for stdio is ftruncate().

The Boost.Interprocess library defines a portable truncate function. For some reason it is not documented, but you can find it this header file.

It'll depend on the OS. Most OSes support this, but in different ways. On Windows, there's a SetEndOfFile(). On Unix and similar systems, you lseek to where you want the file to end, and do an lwrite of zero bytes there. Other OSes undoubtedly use other methods.

I bit the bullet in the end and read the part of the file to be kept to an array then re-wrote it. It's not the best solution - but as the files will always be small I have decided to accept this method.

Related

What is the fastest method to read STDIN data into console app with C++

I have a console app written with C++ that needs to accept text input from another process via writeline (followed by a deadline.) I'm assuming that such needs to be done via STDIN, but it also needs to work in the fastest way possible. My console app then needs to reply to the process back.
I haven't done console programming for awhile now, but I remember from C classes at school that there's a lot of C-type functions, like fgets, getline, etc. but what I remember is that they seemed to be quite slow.
So is there any way to do this exchange (again, "quick in and then out") with WinAPIs?
The fastest method in theory will almost certainly be the system
level input routines, since both the stdin (in C, but also
available in C++) and std::cin build on these. On the other
hand, they have generally been optimized for the platform, so
unless you can find the optimal configuration yourself (e.g.
things like buffer size), you might not gain much, if anything:
calling read (Unix) or ReadFile (Windows) for each character
will probably be slower than using something like
std::getline.
The other question is what you plan on doing with the data after
you've read it. Functions like read or ReadLine give you
a buffer (char[]) with a certain number of characters; you
then have to analyse it, break it into lines, etc. Functions
like std::getline give you an std::string with the line in
it. If you're a really skilled C++ programmer, you can probably
organize things so that the actual data are never moved from the
char[], but this would require re-implementing a lot of things
that are already implemented in the standard library. The use
of templates in the standard library means that you don't have
to implement nearly as much as you would have to otherwise, but
you'll still need to create an equivalent to std::string which
maintains two iterators (char const*) rather than the data
itself.
In the end, I'd start by writing the application using
std::getline and std::string. Once it's working, I'd see
what its actual performance is, and only then, if necessary,
consider ways of improving it.

What should i do if i want to use functions that are not standard and are due to compiler specific API?

I have been using the very very old Turbo C++ 3.0 compiler.
During the usage of this compiler, I have become used to functions like getch(), getche() and most importantly clrscr().
Now I have started using Visual C++ 2010 Express. This is causing a lot of problems, as most of these functions (I found this out now) are non-standard and are not available in Visual C++.
What am I to do now?
Always try to avoid them if possible or try their alternatives :
for getch() --- cin.get()
clrscr -- system("cls") // try avoiding the system commands. check : [System][1]
And for any others you can search for them .
The real question is what you are trying to do, globally.
getch and clrscr have never been portable. If you're trying
to create masks or menus in a console window, you should look
into curses or ncurses: these offer a portable solution for
such things. If it's just paging, you can probably get away
with simple outputing a large number of '\n' (for clrscr),
and std::cin.get() for getch. (But beware that this will only
return once the user has entered a new line, and will only read
one character of the line, leaving the rest in the buffer. It
is definitely not a direct replacement for getch. In fact,
std::getline or std::cin::ignore might be better choices.)
Edit:
Adding some more possiblities:
First, as Joachim Pileborg suggested in his comment, if
portability is an issue, there may be platform specific
functions for much of what you are trying to do. If all you're
concerned about is Windows (and it probably is, since system(
"cls" ) and getch() don't work elsewhere), then his comment
may be a sufficient answer.
Second, for many consoles (including xterm and the a console
window under Windows), the escape sequence "\x1b""2J" should
clear the screen. (Note that you have to enter it as two
separate string literals, since otherwise, it would be
interpreted as two characters, the first with the impossible hex
value of 0x1b2.) Don't forget about possible issues of
redirection and flushing, however.
Finally, if you're doing anything non-trivial, you should look
into curses (or ncurses, they're the same thing, but with
different implementations). It's a bit more effort to put into
action (you need explicit initialization, etc.), but it has
a getch function which does exactly what you want, and it also
has functions for explicitly positionning the curser, etc. which
may also make your code simpler. (The original curses was
developed to support the original vi editor, at UCB. Any
editor like task not being developed in its own window would
benefit enormously from it.)
Well,
People, i have found the one best solution that can be used everywhere.
I simply googled the definitions of clrscr() and gotoxy() and created a header file and added these definitions to it. Thus, i can include this file and do everything that i was doing prior.
But, i have a query too.
windows.h is there in the definition. suppose i compile the file and make a exe file. Then will i be able to run it on a linux machine?
According to me the answer has to be yes. But please tell me if i am wrong and also tell me why i am wrong.

What is the proper way to work with files in C++?

I'm studying C++, now I'm reading about working with files. As I have read, there is quite a lot of variants. So I wanna ask, what is the right way to work with files in C++? Using fstream(ifstream and ofstream)? I have read some opinions that fopen works much faster, so it is better to use it, but it will be no C++.
Thanks for attention!
Use ifstream and ofstream when working in C++. It should not be much slower than FILE*, but is much safer.
See this related question.
I agree with Juraj's assessment of i/ofstream vs. FILE*, I just wanted a word about memory-mapped files. In Boost.SpiritClassic, there's a lesser-known gem called a mmap_file_iterator:
http://www.boost.org/doc/libs/1_47_0/boost/spirit/home/classic/iterator/file_iterator.hpp
I believe that it will memory-map your file if you're in a windows or POSIX environment, and it is a RandomAccessIterator, rather than a Input/OutputIterator.
As for what method is "proper", it all depends on your application's requirements. It is definitely good to explore all of your options and compare the results along as many dimensions as you can conceive.

Is it a good idea to save/load an array of struct?

I was wondering if it was a good idea to load/save an array of a certain type of structure using fstream. Note, I am talking about loading/saving to a binary file. Should I be loading/saving independent variables such as int, float, boolean rather then a struct? The reason I ask that is because I've heard that a structure might have some type of padding which might offset the save/load.
A structure may contain padding, which will be written to the file. This is no big deal if the file is going to be read back on the same platform, using code emitted by the same compiler that did the write. However, this is difficult to guarantee, and if you cannot guarantee it, you should normally write the data in some textual format, such as XML, json or whatever.
Without serialization, your binary data will not be portable across different platform (and compilers). So if you need portability, then you need to serialize the data before storing it in file as binary.
Have a look at these:
Boost Serialization Tutorial
Boost Serializable Concept
It's not deprecated (it's not part of any formal spec, where should it be deprecated?), but it's extremely not portable and probably the worst way to go about serialising stuff. Use Boost.Serialization, or a similar library.
As you pointed out in your answer this will happen with writing structs this way. If you want your files to be portable across platforms, e.g. file being written on Linux i686 to opened by Solaris on Sparc then even writing individual float's won't work.
Try writing your data to something like text or XML and then zip/tar the files to make one document of them.
As Neil said, prefer textual representation of data. The XML format may be overkill. Simpler versions are Comma Separated Value (CSV) and one value per text line.

File management in C++

I have a requirement for reading, updating and deleting a file. I want to write a class for this.
For example
class FileManagement {
private:
fstream myFile;
public:
void read();
void update();
void delete();
};
My question is while updating is it possible to delete only one line in a file in C++ and should be portable, if it is possible how we can achieve this.
Other question is if above option is not possible how we can achieve the above.
In C++ how we can delete a file in portable way.
Thanks!
Use standard C/C++ functions fopen(), fread(), fwrite(), rename() and remove() for that. http://www.cplusplus.com/reference/clibrary/cstdio/
I recommend Boost Filesystem.
Its description reads:
"The Boost Filesystem Library provides portable facilities to query and manipulate paths, files, and directories."
You appear to be asking two different questions at once, in a confusing way.
To delete a file, use the remove function, found in stdio.h.
To erase one line of a file, you have to read the entire file and write it back out with the line removed. There is no library routine for this. The standard "safe" technique is to read the entire file, write it back out (with the line you don't want removed) to a new file in the same directory, fsync the new file, close it, then rename the new file to the old name. If you don't care about concurrent readers or the computer crashing in the middle of the operation, you can instead open the old file read/write, read its contents into memory, rewind the file handle, and rewrite it directly.
You should look at the posix standard, and find the file operations (like fopen()). Where platforms do not support posix, or diverge from the standard, you'll likely need to
#ifdef NONPOSIXOS1 // really, this should be a good identifier of hte OS
// write code to handle the special case
#else
// write code to handle the posix compliant case
#endif
Most systems will accept posix compliant statements. You could always just define abstract base class and create different concrete implementations that use whatever platform specific instructions you need. You could have one if def that instantiates the correct concrete class.
If you are looking for a higher-level C++ library that is object-oriented and can handle both filename manipulation and file I/O, POCO is a decent choice:
http://pocoproject.org
ACE is an older, battle-tested framework that includes lots of I/O support. It's commonly used for it's excellent CORBA support, but there's a lot in there:
http://www.cs.wustl.edu/~schmidt/ACE-overview.html
And, finally, there's QT. Normally known for its cross-platform UI library, QT actually includes several other useful pieces (including file management and I/O), and you don't even have to link in the UI stuff if you don't need it.
http://qt.nokia.com/
If you'd rather not bring in another framework, I would recommend rolling your own File I/O classes using boost::filesystem and either the standard iostream or stdio functions. You can use the interfaces in the above frameworks as a reference, but you will also want to familiarize yourself with modern C++ design, as demonstrated by Boost and explained in Modern C++ Design.