Odd fstream issue - c++

I've got an odd error with all my programs I've written no longer reading the files they're referenced to even if they're in the same directory. I tried old programs that I've written and tested and haven't touched for months yet now they return my ERROR message. I even wrote a simple program to test it:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream openFile;
int num, cnt=0;
openFile.open("data.dat");
if (!openFile) {
cout << "ERROR opening file" << endl;
} else {
cout << "I'm open!" << endl;
while(openFile >> num)
cout << num << endl;
cnt++;
}
cout << cnt << endl;
system("PAUSE");
return(0);
}
Information on file:
1
2
5
66
9
4
2
This returns the ERROR message and cnt at 0. The file is located in the exact same directory as the executable.
What exactly could be causing this? Is there an issue with my program?

Related

c++ fstream read() function not working

Why my following code fails to read single integer from file?
It displays "fail() reading" followed by "0".
On linux ubuntu gcc compiler.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream fout2("int_data",ios::binary|ios::out);
int a = 2;
fout2.write((char*)&a,sizeof(a));
int b=0;
ifstream fin2("int_data",ios::binary|ios::in);
fin2.read((char*)&b,sizeof(b));
if(fin2.fail())
cout << "fail() reading" << endl;
cout << b << endl;
}
This could fail for a couple reasons:
Your OS may be protecting you from opening a file that is currently opened for writing
You may not have flushed your data to the file
You can solve both of these by using close before you construct fin2:
ofstream fout2("int_data", ios::binary);
const int a = 2;
fout2.write(reinterpret_cast<const char*>(&a), sizeof(a));
fout2.close();
int b = 0;
ifstream fin2("int_data", ios::binary);
if(!fin2.read(reinterpret_cast<char*>(&b), sizeof(b))) {
cout << "fail() reading" << endl;
}
cout << b << endl;;
Live Example

copy text from one file to another

I have tried two different while loops. I think they have a similar problem. Neither of them terminate or give any output.
The task is to copy (byte for byte) one file into another. The file does not have to have endlines, nor does it have to be a .txt file (it could be .exe...).
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
char c, c1, c2;
ifstream inFile;
ofstream outFile;
inFile.open("blackbird.txt");
if (inFile.fail())
{
cout << "\nThe file was not successfully opened for reading."
<< "\nPlease check that the file currently exists.\n\n";
exit(1);
}
cout << "\nThe file has been successfully opened for reading.\n\n";
outFile.open("blackbird_copy.txt");
if (outFile.fail())
{
cout << "The file was not successfully opened for writing" << endl;
exit(1);
}
cout << "The file has been successfully opened for writing.\n\n";
//outFile << "Hello";
// 1) this loop doesn't terminate. 2) the computer doesn't know what c1 is.
/*
while (inFile.get(c1))
{
outFile << c1;
cout << c1;
}
*/
// This one is no better
/*
while (inFile.good())
{
inFile.get(c);
outFile << c;
}
*/
inFile.close();
outFile.close();
// read contents of blackbird_copy to check our work.
inFile.open("blackbird_copy.txt");
while (inFile.get(c2))
{
cout << c2;
}
cout << endl << endl;
return 0;
}
inFile.get(c1) Reads one character and stores it to c1 if available. Otherwise, leaves ch unmodified and sets failbit and eofbit.
You can use inFile.eof() to check whether the end of the file has been reached.

Ifstream file does not open although everything seems in place (c++)

I'm trying to write a program to parse the first and sixteenth columns of a CSV file (converted into .txt). I have the CSV ("posts.txt") document in the folder with the executable. But, whenever I try to run the executable, my program delivers that it cannot open the file (or that "!infile.is_open()"). Mind giving me some assistance? I'm running in Xcode 3.2.3 on Mac OSX 10.8.3. The code is shows below.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string.h>
using namespace std;
void answeredPostGrabber()
{
ifstream inFile("posts.txt");
string postNumber;
string answerNumber;
string throwAway;
if(inFile.is_open())
{
while(inFile.good())
{
getline(inFile,postNumber,',');
cout << postNumber << ",";
for(int y=1;y++;y<16)
{
getline(inFile,throwAway,',');
}
getline(inFile,answerNumber,',');
cout << answerNumber << endl;
ofstream edges;
edges.open("edges.txt",ios::app);
edges << postNumber << "," << answerNumber<< endl;
edges.close();
ofstream nodes;
nodes.open("nodes.txt",ios::app);
nodes << postNumber << "\n" << answerNumber << endl;
nodes.close();
getline(inFile,throwAway);
}
}else cout << "ERROR: Unable to open file." << endl;
}
int main ()
{
answeredPostGrabber();
return 0;
}
Thank you in advance!
I have the CSV ("posts.txt") document in the folder with the executable.
The file should be present in the current working directory of your process, which may or may not be the same directory where the executable lives. If in doubt, try specifying the full path in ifstream inFile(...); to see whether that changes things.
Additionally, the file needs to have the correct permissions to ensure that it's readable by the process.

How to read and write input file and output file

I am trying to run the following program:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
double first=1.49, second=2.59, third=3.69, fourth=4.79;
inFile.open("prices.txt");
char response;
if(!inFile.fail())
{
cout << "A file by the name prices.txt exists.\n" << "Do you want to continue and overwrite it\n" << " with the new data (y or n);"; cin >> response;
if(tolower(response) == 'n')
{
cout << "The existing file will not be overwritten." << endl;
return -1;
}
}
outFile.open("prices.txt");
if (inFile.fail())
{
cout << "\n The file does not exist and can not be opened" << endl;
cout << "The file has been successfully opened for output." << endl;
outFile << first << "\n" << second << "\n" << fourth << "\n" << endl;
outFile.close();
exit(1);
cout << "The file has been successfully opened for output. " << endl;
outFile << first << "\n" << second << "\n" << third << "\n" << fourth << endl;
outFile.close();
return 0;
}
}
Yet this program will not write the values to the prices.txt file. If you run the program once it says the file does not exist. Running it a second time says the file is already there and if you want to overwrite it. The thing is searching my Mac I cannot find this file anywhere.
Any ideas what I am doing wrong with running it in Xcode? A friend runs the exact same code in Visual Studio 2008 and it works. Any help is appreciated.
You need to set the working directory for the executable since you are assuming that your data files are in the current working directory. In Xcode 3.x you set this in the first tab of Get Info for the executable. In Xcode 4.x it has been moved, but the principle is the same.
Alternatively you can change your data file paths (e.g. make them absolute) so that you do not make assumptions about the current working directory.
You may not have permission to write into the directory that you are trying to save the file too.
Also, there is an error in your program and I am sure if it is there for debugging reasons. You have
outFile.close();
exit(1);
But then shortly there after you try to write to the file, then close it again.

XCode will not take input from a file

For some reason, Xcode will not take input from a file, while Visual C++ will.
When I run this program in xcode, the variables numberRows and numberCols stay 0 (they are initialized to 0 in the main function).
When I run it in Visual C++ they become 30 and 30 (the top line of maze.txt is "30 30" without the quotes).
Any ideas why this is happening?
void readIn(int &numberRows, int &numberCols, char maze[][100]){
ifstream inData;
inData.open("maze.txt");
if (!inData.is_open()) {
cout << "Could not open file. Aborting...";
return;
}
inData >> numberRows >> numberCols;
cout << numberRows << numberCols;
inData.close();
return;
}
There is something else wrong.
Unfortunately it is hard to tell.
Try flushing the output to make sure you get the error message:
void readIn(int &numberRows, int &numberCols, char maze[][100])
{
ifstream inData("maze.txt");
if (!inData) // Check for all errors.
{
cerr << "Could not open file. Aborting..." << std::endl;
}
else
{
// Check that you got here.
cerr << "File open correctly:" << std::endl;
// inData >> numberRows >> numberCols;
// cout << numberRows << numberCols;
std::string word;
while(inData >> word)
{
std::cout << "GOT:(" << word << ")\n";
}
if (!inData) // Check for all errors.
{
cerr << "Something went wrong" << std::endl;
}
}
}
interesting, so I followed the following suggestion from this post http://forums.macrumors.com/showthread.php?t=796818:
Under Xcode 3.2 when creating a new
project based on stdc++ project
template the target build settings for
Debug configuration adds preprocessor
macros which are incompatible with
gcc-4.2:
_GLIBCXX_DEBUG=1
_GLIBXX_DEBUG_PEDANTIC=1
Destroy them if you want Debug/gcc-4.2
to execute correctly.