Reading ppm file C++ - 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.

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.

Opening file to read structure array

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())

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.

Failbit set when trying to read from file - why?

I'm trying to write a function that automatically formats XML-Strings; but I'm already failing when I try to read text from a file and write it into another one.
When I use my function sortXMLString()
bool FormatXML::sortXMLString()
{
string XMLString;
ifstream fin("input.txt");
fin.open("input.txt", ios::in);
ofstream fout("output.txt");
fout.open("output.txt", ios::out);
if (fin.is_open() && fout.is_open())
{
if (fin.good()) cout << "good" << endl;
if (fin.fail()) cout << "fail" << endl;
if (fin.bad()) cout << "bad" << endl;
while (getline(fin, XMLString))
{
//TODO: Formatting
fout << &XMLString << endl;
}
fin.close();
fout.close();
}
else return false;
return true;
}
I will get the output "fail", but the function never enters the while-loop. The function returns true.
It doesn't matter what I write into my input.txt (a single letter, a single number, multiple lines of text or even nothing), the failbit will always be set before getline can even be reached.
Why is this/ how can I properly read out of my file?
ifstream fin("input.txt"); will open the file with fin as stream object why calling open member function again ? same goes for fout object too.
Calling open on an already open stream fails, meaning the failbit flag is set to true.
Just open once
ifstream fin("input.txt");
ofstream fout("output.txt");

Unable to print text from file

I'm trying to write a simple program that will print the contents of a text file one line at a time. However, whenever I run the program i just get a blank screen. I'm certain the file I am trying to read contains text over several lines. Any help as to why this isn't working would be super helpfull.
bool show() {
string line;
ifstream myfile;
myfile.open("tasks.txt", ios::app);
while (!myfile.eof()) {
getline (myfile, line);
cout << line << endl;
}
myfile.close();
return true;
}
The problem might be that you are using ios::app with ifstream (input stream), which makes no sense.
According to this,
ios::app: All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
Try this:
std::string line;
ifstream myfile ("tasks.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
std::cout << line << std::endl;
}
myfile.close();
}
Did you check return value of myfile.isopen()? Perhaps the file isn't there or you don't have read permission.
Oh yes, I missed that - the append flag. Should be ios::in