redirecting input in c++ - c++

i was told that to redirect from standard input to file i need to do the following:
static std::ifstream inF("inpur.txt");
std::cin.rdbuf(inF.rdbuf());
and every call to std::cin will be redirected to input.txt.
but my question is: do i need to open inF? and if i do, where do i need to do this?

You opened it by calling it with the string constructor.

That's the beauty. You already did so while declaring the object and passing the string to the explicit constructor of ifstream.
The file is opened in TEXT mode.
Refer this

Your code as-is fine. Do make a backup though of the original cin.rdbuf -- you may need to reset it in case of an error.

Related

preferred c++ i/o stream method: fstream or ifstream/ofstream or something else entirely?

I have created a roster program that accepts user input to create/write/delete information into and out of a specified text file. My issue now becomes wanting to create a lasting text file that isn't overwritten every time I re-run the program and am not sure if using fstream or a combination of of/ifstream is better practice, or if there is maybe a third option I missed when checking the reference docs.
Right now I am simply using: std::ofstream outfile("roster.txt"); which works, until I kill and re-run the program to which my text file is now wiped clean.
check out the append flag. it writes to the end of an existing file.
http://www.cplusplus.com/doc/tutorial/files/
example here.
std::ofstream outfile("roster.txt" , ios::app)

The program doesn't seem to be saving the input data correctly (c++)

So, I want my program to read data from a file, and save it into different quarter1, quarter2,quarter3, quarter4 depending of it's date, but it doesn't seem to work properly and still don't know why, I've been trying to debug and I'm pretty sure it fails when saving at saveQuarters or existeix which is basically a dichothomic search which returns if the code exists and if it exists, it returns the position. This is the code:
I just skimmed through some of the stuff you had so this suggestion may not work, but you can try declaring your file as input or output. Perhaps that could be the problem.
Some thing like:
string fileName = "data.txt";
ifstream dataFile;
dataFile.open(fileName, ios::in);
Doing this:
fitxerCens >> taulaCens[i].stateName;
Will grab an entire line of the data file until it sees a space is correct.

how do i legitimately change filename value of ofstream object?

I'm having troubles with ofstream , which is - when I change value of ofstream object like this
ofstream o_save;
/*code*/
o_save = ofstream(filename); //Problem is here
...the line above completely erase contents of file.
The question is how do I legitimately change filename value of ofstream object ?
P.S. I cant define it when I declare it, because I want it global and I'm not sure which save file I select.
The question is quite vague and contradictory, and the OP seems to have slept after asking the question. So I shall try to peek inside his head and try to elaborate what he wants.
For opening a file, there are many modes for that. Open it like this.
ofstream o_value ;
o_value.open("file.txt") ;
If you want to preserve the original contents of that file, use..
o_value.open("file.txt", ios::app) ;
If you want to close it later and open another one, close using...
o_value.close() ;
Chaning of file names is normally not allowed in case of ofstream. You can use rename from <cstdlib>. You can delete a file though using remove("file.txt") in <cstdio> .
What does it mean to "change the name" of an ofstream object?
The only "name" an ofstream object has is the name of the
variable. An ofstream object is a data stream. You can (on
some systems) change the name of the file it is associated with,
using rename, but somehow, I don't think this is what you want
either. You can also close the stream, and reopen it on another
file.
You cannot assign between iostream objects. If worse comes to
worse, you can declare the global object as a pointer, and
assign to it (using *o_save to write to it).
Finally, the standard says that when you open an ofstream, you
truncate the file, if one exists. If this is not what you want
to do, then you have to add some flags to the open mode. If you
add std::ios_base::app, for example, you will no longer
truncate the file, and all writes will be to the end of file
(atomically, if the system supports it). Alternatively (albeit
quite surprising), you could add std::ios::in to the flags;
this will fail if the file doesn't exist, but will allow writing
anywhere in the file. This is the only way to open a file for
writing if you want to be able to write anywhere in the file,
even if you don't want to read it.
The ofstream does not have some kind of an abstract name attribute, the name is just a parameter to some of its member functions, in that sense asking how to
change filename value of ofstream object
is meaningless.
In general you can rename files with std::rename from <cstdlib> or use Boost.Filesystem.

when would failbit be set while executing a getline function call in c++

when would getline in c++ fail?
I have a big snippet of code which I am unable to paste in its entirety for multifarious reasons. I am trying to read from a file , which I know exists and contains data, using getline in C++. But getline fails returning error 123-invalid name(output of getlasterror). I looked up the error code which baffles me even more.
I do error check while opening the file. So I am positive that I have the handle to the file.
Please bear with me for not pasting the code. I am new to c++ and especially in windows. Any suggestions or insights about getline would help. I am trying to read a file which is dumped by a compiler.
This is an extract from the code
ifstream inFile("C:\...\ash.txt",ios::in);
string singleLine;
getline(inFile,singleLine);
singleLine is empty ! I am doing something silly..pls point that out to me! appreciate it
IMPORTANT EDIT:
I checked for the ios members and found that fail bit is set. Why would the fail bit be set? the file does exist and also I was wondering if how windows exposes file extensions could cause a problem . That doesnt seem to the problem. What am i missing?
GetLastError only tells you about Win32 API calls, which std::getline is not.
Check the members of the iostream that failed, e.g. rdstate().
Calling ios::exceptions(eofbit | failbit | badbit) before getline and catching the resulting exception might or might not get you a more descriptive error message.
If the fail bit is set, it is probably because you didn't successfully open the file. Check whether ifFile.is_open() returns true; if not, then then probably indicates that the file is not open correctly. You might not have permissions, or you may need to escape the string properly, or the file may be locked.
You should also check if fail is set both before and after the call to getline. If it's before, that probably means that the file isn't open. If it's after, it could mean that the file is empty.
It may be the case that Windows is hiding the true file extension from you. The file name might actually be named ash.txt.txt, for example, if you have Explorer configured to hide file extensions. That might be worth investigating if the file isn't open.
Do you need to escape the backslashes in the file path?
It failed to open the file.
This is becuase you did not specify the correct path.
This is because you used the ancient windows convention of \ as a path separator.
Which also happens to be the escape character in C.
Which is why Windows lets you use / as a path separator (and has done for over a decade) because the use of '/' is so error prone.
Your path should be:
ifstream inFile("C:\\...\\ash.txt");
// Or my preference
ifstream inFile("C:/.../ash.txt");
Or even better use boost.
Getline IIRC is meant for c_strings and the string is the first argument, not the second.
http://www.cplusplus.com/reference/iostream/istream/getline/
You're attempting to use a normal string, which (I could be wrong) doesn't work with getline.

changing part of a file in C++

Consider i have a file, 'emp.txt' whose content is,
EmpNo. Name Phone No. Salary
1 ABC 123 321
2 CBA 456 543
Now i want to change the phone no. 1st Employee alone. When i tried using ios:ate, all the contents of the file got deleted and the new phone no. got inserted. How can i solve this?
If you open a file for just output, the library usually truncates the existing file. To change the existing contents of a file, the easiest way is to open it in 'read/write' mode so that you can seek to the correct position and partially overwrite its contents.
Try something like:
std::fstream filestream( "emp.txt", std::ios_base::in | std::ios_base::out );
or if you're using C streams:
FILE* f = fopen( "emp.txt", "r+" );
Change mode of Stream opening
See all possible Modes here
For your example I think it would better just is to load the whole file, do your change and then write back the whole file. If the file is large then not.
In Windows, MapViewOfFile() works great in the special case where you are just overwriting digits in-place and the tail of the file need not move. If you DO need to rewrite the entire file, there's a Wikipedia entry on "Transactional NTFS" for ultimate peace-of-mind.
Memory-mapped-files in my experience work REALLY well. If your process crashes, typically the very last byte you happened to write will still be flushed to disk correctly, since Windows robustly knows which pages are dirty.
Which SUGGESTS "padding your records" so that even typical Address-changes might be accomplished without moving the tail of the file.