File not reading in correctly - c++

I have a program that reads in a file. All my classes compile fine, but there seems to be an error when I read in the file. Eclipse shows an empty string is being read in (""), which is not what I want.
I have the code for my main below with a while loop. I placed the loop just to see how it would run when debugging, and it runs an infinite loop since it is always reading in "", and never reaches end of file. I have put the file in the working directory and every other folder just to be sure, but it is always doing this even though the file is full of strings and integers. Is there anything I am doing wrong here?
#include "Translator.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
ifstream readFile;
readFile.open("sample.html");
while (!readFile.eof()) // for debugging purposes only
{
string x;
readFile >> x; // x is "" everytime through the loop
readFile >> x; // x is also ""
}
Translator t(readFile);
readFile.close();
return 0;
}

My guess is that your file did not actually open, and the eof bit was therefore not set. You never test whether the file was opened successfully. It could be that your working directory is not what you think it is, or the file is locked by another process (perhaps open in a text editor).
Officially, you can test readFile.fail() after you try opening.
I've found that checking readFile.good() is fine too - in fact you can use that as your loop condition.
I prefer the positive message of 'good' in my code, rather than the potentially upsetting 'fail'.
You should also test your stream as WhozCraig suggested in comments, when you are reading data. You cannot assume that the operation was successful. If it fails for reasons other than EOF, you need to know.
For these reasons, don't use readFile.eof() as your loop condition.

Related

I can't read from a file

I wrote a code to make "text1.txt" file. It worked correctly, then I've been trying to read from the file, but every time is_open() function doesn't return true. Even so I copied other codes in the way exactly they are in different compilers, but it never works. How will I solve this:(
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file1("text1.txt");
string str;
if(file1.is_open()){
while(getline( file1, str)){
cout<<str;
}
}
else
cout<<"the file is not open"<<endl;
return 0;
}
How are you running your program?
The most common cause of this I've seen is that you're running your program inside an IDE (like Visual Studio), and your current directory isn't where you think it is.
Try putting in the full path to the file and see if your problem disappears.

Reading from ifstream until file ends

I'm writing simple console application in cpp but none of my approaches to write it were succesful. I'm trying to read row after row from ifstreamed file until the file ends.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
void lowtempbin(string inpfile){
ifstream wyciag(inpfile.c_str());
string row_temp_bin;
int i=0;
while(getline(wyciag, row_temp_bin)){
i++;
cout<<i;
}
}
int main(){
lowtempbin("danesystemy.txt");
return 0;
}
Why the program doesn't enter while loop, and if getline does load nothing, then whole function should return 0? And then code after while is executed (not inside). I'll add that I pass as the argument to lowtempbin()inside main, name of the file that is in the same directory as executable (in code:blocks /project/bin/Debug). Also when I debug the application, while loop is never executed, as if getline returns negative value.
Code shoud cout all numbers, one for every row, but it just returns 0;
The program compiles and produces the expected result when ran.
Your problem seems to be one of the following:
The filename is incorrect.
The file is not in the same directory as the executable.
The file doesn't exist at all.

why SDL_RWFromFile( file ,"w+") does not read and write like its supposed to? it only opens file for writing

can someone explain to me why this code won't work as expected. It seems SDL_RWFromFile using the w+ mode only works for writing and Not READING AND WRITING as its supposed to... what am i doing wrong
i dont want to have a different handler for reading and a different one for writing
#include <iostream>
#include <SDL.h>
using namespace std;
int main(int argc,char* args[])
{
SDL_Init(SDL_INIT_VIDEO);
int scores=2;
SDL_RWops* rwScore=SDL_RWFromFile("highscore.dat","w+");
SDL_RWwrite(rwScore,&scores,sizeof(int),1);
int fromfile=0;
SDL_RWread(rwScore,&fromfile,sizeof(int),1);
cout<<fromfile<<endl;
return 0;
}
this prints out 0;
Your problem is in "w+" that means:
write/update: Create an empty file and open it for update (both for
input and output). If a file with the same name already exists its
contents are discarded and the file is treated as a new empty file
See the description of all flags here:
https://wiki.libsdl.org/SDL_RWFromFile

A running executable that modifies itself

I have a Visual Studio 2008 C++ project for Windows CE 5 where I would like the currently running executable to modify itself.
Specifically, I would like to be able to read/write some data stored within the exe file itself. I do not need (or wish to) modify executable code.
In regular windows, I could use a string resource and the UpdateResource function, but that doesn't exist in WinCE.
CreateFile, unfortunately, fails because the file is already in use.
Does anybody have any other suggestions?
First, why do you need to do this? You should be able to do this with other methods.
I'm not particularly familiar with Windows-CE, but if you need to, you can probably copy the file, edit the copy, delete the first, and then run the other. That's an inefficient way, but if you only need to do it once or twice in the span of the program and speed isn't a concern, I guess you could do it:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]) {
// Check if this IS the copy:
if (argv[0].find(argv[1]) != string::npos) {
system("taskkill -IM myOLDfile.exe"); // Stop the old one running,
system("del myOLDfile.exe"); // Then delete it.
}
ifstream myself(argv[0]); // argv[0] is the program itself
string fullcode;
string line;
if (file.is_open()) {
while (file.good()) {
getline(myself, line);
line.append("\n");
fullcode.append(line);
}
}
myself.close();
// Do whatever you need to do to the code here.
ofstream newcode("myNEWfile.exe");
newcode.write(fullcode);
newcode.close();
system("myNEWfile.exe myNEWfile.exe"); // Starts new file. Also, not a typo.
}
Good luck on your project!

C++ program sees an included .txt file as code

I am just learning the very basic aspects of input/output streams, and can't seem to have my program read a text file. It gives me errors that indicate it is trying to read the .txt file as C++ code, while I am just using values in there to test my stream.
These are the contents of my included .txt file:
12345
Success
And here is the main program's code:
#include <fstream>
#include <iostream>
#include "C:\Users\Pavel\Desktop\strings.txt"
using namespace std;
int main (int nNumberOfArgs, char* pszArgs[])
{
ifstream in;
in.open("C:\Users\Pavel\Desktop\strings.txt");
int x;
string sz;
in << x << sz;
in.close();
return 0;
}
The first error message I receive is "expected unqualified-id before numeric constant" which tells me the program is attempting to compile the included file. How can I prevent this and have the text file read as intended?
Don't #include your .txt file. Includes are for source code. They textually insert the file into your code, as if you had actually copy-pasted it there. You shouldn't be #includeing a file you're opening with an ifstream.
Opening files on the filesystem at runtime doesn't require any mention of that file's name in the source code. (You could, for instance, ask the user for a filename, and then open it just fine!)
The case where you might #include data in your source would be if you wanted to have that data embedded into the executable of your program (and thus not rely on a file that was on the filesystem when running). But to do that, you have to format your file as a valid C++ data declaration. So it would not be a .txt file at that point.
For instance, in strings.cpp
#include <string>
// See http://stackoverflow.com/questions/1135841/c-multiline-string-literal
std::string myData =
"12345\n"
"Success";
Then in your main program:
#include <iostream>
#include <sstream>
#include "strings.cpp"
using namespace std;
int main (int nNumberOfArgs, char* pszArgs[])
{
istringstream in (myData);
int x;
// Note: "sz" is shorthand for "string terminated by zero"
// C++ std::strings are *not* null terminated, and can actually
// legally have embedded nulls. Unfortunately, C++ does
// have to deal with both kinds of strings (such as with the
// zero-terminated array of char*s passed as pszArgs...)
string str;
// Note: >> is the "extractor"
in >> x >> str;
// Note: << is the "inserter"
cout << x << "\n" << str << "\n";
return 0;
}
Generally speaking, just #include-ing a source file like this is not the way you want to do things. You'll quickly run into trouble if you do that in more than one file in your project (duplicate declarations of myData). So the usual trick is to separate things into header files and implementation files...including the headers as many times as you want, but only putting one copy of the implementation into your build process.
An #include directive works the same way regardless of the extension of the file being included - txt, h, no extension at all - it doesn't matter. How it works is the contents of the file are pasted into your source file by the preprocessor before that file is passed to the compiler. As far as the compiler is concerned, you might as well have just copied and pasted the contents yourself.