Writing to second line

Hi all

I have two what I hope are simple questions.

using namespace std;
COLORREF centerColor;
POINT cent;
int main()
int int_var;
HDC hdc_ = GetDC(GetDesktopWindow()) ;  //I'm not sure if this is right or what exactly it does.
cent.x = 500;
cent.y = 500;
centerColor = GetPixel(hdc_, cent.x, cent.y);

ofstream ofs("output.txt");
ofs << int_var;

cout << GetPixel(hdc_, cent.x, cent.y) << endl;
cout << endl << "information has been transferred. press any key to close...";
return 0;

1. My code is supposed to find the RGB of a pixel on screen and write the information to the first line of outputs.txt. I don't think it does however. The numbers that appear on the screen are different to what is written in the txt file. For example, the program says 15794175, but the txt file has 4194816 written to it. What have I done wrong or why is it doing this?

2. I ultimately want to write the values of five pixels to the txt file, with each number on a different line. How do I make it so the value is written to the second, third etc line?
1. You are writing the value of the uninitialized variable int_var to file. I think it is centerColor that you want to write.

2. You can use endl with ofstream just like you do with cout. Or you can output a new line character '\n', ofs << '\n';. The difference is that endl will flush the stream while '\n' might not do that.
But with a file, the stream is flushed just before the file is closed, so it's often not important. Performance might be better if the system is allowed to handle it.
Thank you for your helps. I have everything working now.

I have one last question though. When I run the program a second time, it replaces whatever is there. Is there a way that I can, say, replace the second line but without aletering the first line?
Did you want to replace an existing second line, or replace a blank line with a new one (ie append to the file)? (You code is only writing one line at a time to the file...)

If possible, I would like to replace the existing second line.
It's would be quicker to code by just reading the existing two lines and then writing out the first one along with the new second line.

Otherwise you'd have to open the file for read-write access, seek forward to find the end of the first line, write your new line, and then adjust the position of the end of file (the new file size can be bigger or smaller).

I would go with the read/re-write approach.


I'll try that.
Topic archived. No new replies allowed.