0

I'm trying to write into a file using fstream, but my code is not working. Can you help me what am I doing wrong?

void mem_test() { fstream filepointer; string buffer; if ( filepointer.is_open() ) { filepointer.open("test.t", ios::in | ios::out | ios::binary); getline(filepointer, buffer); getline(filepointer, buffer); filepointer << "TEST!" << endl; } filepointer.close(); } 

My file test.t (Perimssion to read and write the file in linux):

Example Line 1 Example Line 2 Example Line 3 Example Line 4 

Thanks!

6
  • 6
    First thing that I notice, is that you are trying to open a file if it is already open. And, in your code snippet, it won't, ever, be open. Commented Apr 13, 2016 at 15:47
  • @molbdnilo No you should not. It is a simple "typo" i.e. order of commands. Pointing it out in the comments and voting to close is the way to go. Answering it stops it from being able to be automatically deleted. Commented Apr 13, 2016 at 16:03
  • @NathanOliver I would call it a fundamental misunderstanding rather than a typo, but I see your point. Commented Apr 13, 2016 at 16:07
  • I just rolledback your edits, because if you fix your code in the question, the question becomes completely pointless. You should not edit the question to fix problems in the code you were originally asking for. This makes it useless for future readers and invalidates already given answers. Commented Apr 13, 2016 at 18:18
  • Hello. It's not working yet. Commented Apr 13, 2016 at 18:55

2 Answers 2

2

You are checking if the file is open before actually opening the file so it should be:

void mem_test() { fstream filepointer; string buffer; filepointer.open("test.t", ios::in | ios::out | ios::binary); if (filepointer.is_open()) { getline(filepointer, buffer); getline(filepointer, buffer); filepointer << "TEST!" << endl; filepointer.close(); } } 
Sign up to request clarification or add additional context in comments.

Comments

1

No need to do the if ( filepointer.is_open() ) check first which will always return false in this case because the file stream has not yet opened a file yet, as a result your code in the if block will not be executed(opening the file which contradicts what you are trying to check in the first place). So open the file first, then check the stream state for error afterward(i.e use if(filepointer.is_open()) .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.