Opening file to read structure array - c++

I'm a beginner in computer science learning c++.
Every attempt that I make to open a file in my program and read the information into a structure does not work.
Here is what I have written in the function.
void getMemberInfo(Payment member[])
{
ifstream file;
file.open("information.txt", ios::in);
int i = 0;
if (!file)
cout << "\n Error opening file!\n\n";
else
{
while (!file)
{
file >> member[i].ID;
file.getline(member[i].name, 30, '\n');
member[i].member_name = member[i].name;
file >> member[i].payment_due;
i++;
if (file.eof())
break;
}
}
file.close();
}
Any help is appreciated. I'm kind of at a loss of what's wrong.

The error is in the while condition. Just change the condition and it should work
// Instead of !file, use !file.eof()
while (!file.eof())

Related

Weird program behavior when streaming data to files before using seekg and tellg

I'll try to be as clear as I can: Whenever I try to stream data to my file before my 'do' loop and my pointers reading and writing, my program goes nuts! It appears to be running an infinite loop.
fstream fileHandler; //Can also be done via constructor fstream fileHanlder("myData.txt", ios::out);
//fileHandler.open("myData.txt", ios::out);//Default is in AND out
fileHandler.open("test.txt", ios::in | ios::binary | ios::out);
if (fileHandler.is_open()) {
//fileHandler << "anything" <---HERE IS THE PROBLEM
cout << "The file has been opened and edited properly.";
fileHandler.seekg(0, ios::end);
streampos sizeOfFile = fileHandler.tellg();//tellg returns type streampos
fileHandler.seekg(0, ios::beg);
do{
string buffer;
fileHandler >> buffer;
cout << buffer << endl;
}while(!fileHandler.eof());
if ((fileHandler.rdstate()^ifstream::eofbit) == 0) {
fileHandler.clear();
cout << fileHandler.tellg() << endl;
}
fileHandler.close();
} else cout << "There was a problem opening the file!";
My file has nothing but a simple phrase.
EDIT: fixed the title according to new information
Thanks for any attention!
Removing the binary flag fixed it for some reason.

questions on how to open text file properly in c++ programming

first time here. I am a student doing some c++ coding for end year project. The programme that I coded does not read the text file even though everything seems to be in order. Some helps would be fantastic!
void transactionRecords(double total, char answer, string nameT, int HpNo, string address)
{
fstream myFile;
string name;
char idStatus;
double amt, sumAll=0;
myFile.open("transaction.txt",fstream::in);
if (!myFile) cout<<"Unable to Open File under Input Mode";
else
{
while (!myFile.eof())
{
myFile>>name>>idStatus>>address>>HpNo>>amt;
if (myFile.fail()) break;
}
myFile.close();
myFile.open("transaction.txt",fstream::app);
if (!myFile) cout<<"Unable to Open File under App Mode";
else
{
myFile<<nameT<<" "<<answer<<" "<<address<<" "<<HpNo<<" "<<total<<endl;
if (myFile.fail()) cout<<"Error encountered while adding data!\n";
}
}
myFile.close();
}
this is whats in the text file
Johns Y pasir_ris 81231211 4.14
First, I suggest you use the RAII principle when creating files that is:
void myfunction() {
ifstream f{"file.txt"};
// your logic here
// NB -- no need to manually close file, prevents resource leaks
}
There is no need to manually close or open such a file, it is opened by the constructor and closed when the destructor is invoked upon exiting the current scope. This prevents leaks of file handles and is a pervasive technique in C++.
Second, use the standard stream read loop in C++:
while (myFile>>name>>idStatus>>address>>HpNo>>amt) {
// your logic here, the read has succeded
// TODO process myFile, name, idStatus etc.
}
With these changes, your example should look something like:
void transactionRecords(double total, char answer, string nameT, int HpNo, string address)
{
ifstream myFile{"transaction.txt"};
string name;
char idStatus;
double amt, sumAll=0;
if (!myFile) cout<<"Unable to Open File under Input Mode";
return;
while (myFile>>name>>idStatus>>address>>HpNo>>amt) {
// TODO do something here??
}
ofstream tFile{"transaction.txt"};
if (!myFile) cout<<"Unable to Open File under App Mode";
return;
if (!(tFile<<nameT<<" "<<answer<<" "<<address<<" "<<HpNo<<" "<<total<<endl)) {
cout<<"Error encountered while adding data!\n";
}
}
}
You should probably do something in the TODO block, currently you are only storing the last values read? If you only mean to process one line from the file, swap the while loop with an if.

I Can't print out a file that I wrote on

I have created a function to write some data on a text file, and it works fine. I created another function to read in all the content of the file, and print it out for me! But, it is not working for some reason. Could any one help please?
This is my function:
void myClass::displayFile() {
char line[LINE]; //to hold the current line
file.open("data.txt", ios::app);
//keep reading information from the file while the file is open and has data
while (!file.fail() && !file.eof()) {
int lineSize; //to loope through each line
file.getline(line, LINE);
lineSize = strlen(line);
//loop through the line to print it without delimiters
for (int i = 0; i < lineSize; ++i) {
if (line[i] == ';') {
cout << " || ";
} else {
cout << line[i];
}
}
}
file.close();
file.clear();
if (file.fail()) {
cerr << "Something went wrong with the file!";
}
}
Note: The function compiles and the loop is accessible, but the line string is empty.
This is the writing function:
void myClass::fileWriter() {
file.open("data.txt", ios::app);
file << name << ";" << age << ";" << "\n";
file.close();
file.clear();
}
Silly me, the cause of your problem was staring me right in the face from the beginning, and it's the app open-mode that's the problem. It is to open the file in write mode, which means you can't read from it.
And even if you could read from the file, the cursor is placed ad the end of the file the eofbit flag would have been set inside the first iteration anyway.
If you want to read from a file, then either use std::ifstream which automatically sets the in mode if you don't specify a mode, or you have to explicitly set the in mode when opening.

find word in a text in C++ and print some next specific lines

I wrote a code in C++ that writes a .txt file.
Then I want to open the code again and give some information, so I can get a new text depending on what I gave as an input.
For example I want to give the name of a month, and print in another .txt file all the lines that came after the word "November".
I found some solutions, but none of them worked for me!
One solution that I found on stack overflow is the following:
void Keyword(ifstream & stream, string token) {
string line;
while (getline(stream, line)) {
if (line.find(token) != string::npos) {
cout << line << endl;
}
}
cout << token << " not found" << endl;
}
I can't print the next lines with the code above.
Any suggestion would be helpful!
Thanks!
If you want to perform operations on files such as 'Read' and/or 'Write',you might want to search on the net(or if you have a C++ book) on topics such as "File I/O operations using C++". Anyways moving on, C++ has 2 basic classes to handle files which are ifstream and ofstream. And to use them you have to include ethier the header fstream(i.e #include<fstream>) or include them separately as #include<ifstream> and #include<ofstream>. ifstream is basically used for all input operations such as reading files etc. Similarly ofstream is used for all output operations such as writing data to files.
You can open a file and write data to it by doing the following,
ofstream myFile("filename");// Create an instance of ofstream and open file for writing data
and to write data to the file use the << operator like below,
myFile<<data;
Similarly, You can open a file and read data as follows,
ifstream myFile("filename");//Create an instance of ifstream and open file to read data
and to read data from the file use the >> operator as shown below,
myFile>>data;
You can also open a file using the method void open(const char *filename, ios::openmode mode); as shown below,
//Writing only
ofstream outFile;
outFile.open("filename.txt",ios::out);
//Reading only
ifstream inFile;
inFile.open("filename.txt",ios::in);
//For reading and writing
fstream file;
file.open("filename.txt",ios::in|ios::out);
//For closing File
outFile.close();
//or
inFile.close();
//or
file.close();
Note the open() method takes various flags such as ios::in for reading mode, ios::out for writing mode, ios::app for adding data to the end etc.
All of these can also combined by using the bit OR operator | as shown below,
outFile.open("filename.txt",ios::out|ios::app);
There is a lot more in IO. I just covered the things required to start.
Here is the solution to your problem. Try to understand it.
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
ofstream outFile;
ifstream inFile;
char fileName[10],data[50];
int noLines;
cout<<"Enter Month:"<<endl;
cin>>fileName;
cout<<"Enter Number of lines you want to enter:"<<endl;
cin>>noLines;
outFile.open(fileName,ios::out);
cout<<fileName<<"(Enter Data):";
for(int i=0;i<=noLines;i++)
{
cin.getline(data,50);
outFile<<data<<endl;
}
outFile.close();
cout<<"Openening "<<fileName<<" :"<<endl;
inFile.open(fileName,ios::in);
for(int i=0 ;i<=noLines ;i++)
{
inFile.getline(data,50);
cout<<data<<endl;
}
inFile.close();
return 0;
}
OP has found most of the solution already:
string line;
while (getline(stream, line)) {
if (line.find(token) != string::npos) {
cout << line << endl;
}
}
cout << token << " not found" << endl;
But this only prints the lines with the keyword. And always prints the "not found" message. Ooops.
Instead I pitch:
string line;
bool found = false;
while (!found && getline(stream, line))
{ // search for keyword
if (line.find(token) != string::npos)
{
found = true; // found keyword. Stop looking
}
}
if (found)
{ // print out all remaining lines in the file
while (getline(stream, line))
{
cout << line << endl;
}
}
else
{
cout << token << " not found" << endl;
}
The above splits the finding of the token and the printing of the remaining file into two stages for readability. It can be compressed into one loop, but two things make this a sucker bet:
this program will be IO bound. It will spend the vast majority of its time reading the file, so little tweaks that do not address getting the file into memory are wasted time.
combining the loops would require the addition of logic to the loop that would, over along run, dwarf the minuscule cost of switching loops.
Try this:
http://www.cplusplus.com/doc/tutorial/files/
and this:
http://www.cplusplus.com/forum/beginner/14975/
It's about reading and writing files in c++ and about searching in files.

Reading ppm file C++

I am trying to read a ppm file and store its contents in an array. I am starting off by trying to display it but I can't seem to output anything.
char magic;
ifstream myfile;
myfile.open(file,ios::in | ios::binary);
if (!myfile.is_open())
{
cout<<"Failed to open";
}
myfile.get(magic);
if(myfile) cout <<magic <<"not working";
myfile.close();
The file is opened but I can't read it. I have also tried outputting by using the << operators, but no luck there either.
It's probable that your file is being read, but your variable isn't storing all the values therein. I suggest adding this instead of myfile.get(magic):
char magic;
ifstream myfile;
if (!myfile.open(file, ios::in | ios::binary)
{
cout << "Failed to open" << endl;
}
vector<char> magicNumbers;
while (myfile >> magic)
{
magicNumbers.push_back(magic);
}
myfile.close();
As you can see, you should store all the values in some kind of array, here I used a vector for flexibility. The rest is up to you.