am trying to append to file but its not going correctly every time it fail to connect to file

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
	fstream file;
	char word[256];

	file.open("StudentInfo.txt",ios::app);
//file.open("StudentInfo.txt",fstream::app); // wont work too

	if(file.fail())
	{
		cout << " Error opening the file " << endl;
	}

	int i=0;

	while(i < 3)
	{
		file.getline(word,256,'\n');
		cout << word << endl;
		i++;
	}



	return 0;
}

any advise

I can't use ifstream/ofstrem I have to use fstream advise please!

Thanks

Ok first off please take a little more care with the code tags, but I can see you just made a mistake so no problem.

Second you open a fstream BUT write to std::cout...

Then next you can use fstream BUT if it is for output it needs
the std::ios::out flag to be set.

e.g.

file.open("StudentInfo.txt",ios::app|std::ios::out);

hope that helps.

thank you

but what if I want read from the file ?

how can I delete a line from the file ?

thanks

Now I'm completely confused. In your first post you state

am trying to append to file but its not going correctly

The problem is you open the file for append (write at end) then try reading from the file. That's just backwards.

Then:

but what if I want read from the file ?

Open the file for reading, not appending

how can I delete a line from the file ?

You can't -- directly. You need to read the file line by line writing each line to another file. When you get to the line you want deleted, just don't write it. You basically end up making a copy of the file without the lines you want deleted.

This article has been dead for over six months. Start a new discussion instead.