Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writting in files

Status
Not open for further replies.

Casiopea

Programmer
Jan 15, 2003
47
ES
I have created a CFile object and I want to write in it, in fact I get it, but I cannot write on differente lines although I add "file.Write("\n",sizeof("\n"))" I just see
inside the file one very long line.
How can I get it?

Another question is that I give it code for an html file, I mean, <HTML>....</HTML> and the extension is html; is that enough to open it like an html file; I see the icon associated to the file like an html, and it seems it work, but I would like to give it bold letter, center and so on.
 
\n" is a pointer to a string, hence sizeof("\n") returns the size of the pointer to the string (which I guess is 4 on your system).

Anyway, in windows most applications require "\r\n" to mark a new line.

Code:
  CFile f(theFileName,CFile::modeCreate | CFile::modeWrite);
  CString s("<html>\r\n<body>\r\n<b>B</b>old\r\n</body>\r\n</html>");

  f.Write((LPCTSTR) s, s.GetLength());

or if you want to work in unicode aswell
Code:
  #include <string>
  
  // ...
  CFile f(theFileName,CFile::modeCreate | CFile::modeWrite);
  std::string s("<html>\r\n<body>\r\n<b>B</b>old\r\n</body>\r\n</html>");

  f.Write(s.c_str(), s.size());



/Per

www.perfnurt.se
 
> "\n" is a pointer to a string,
String constants are arrays, so depending on the context it may or may not decay to a pointer.

> file.Write("\n",sizeof("\n"));
The first use is a decayed pointer, the second use returns the size of the array.
It is the equivalent of
Code:
char anon[] = "\n";
file.Write(anon,sizeof(anon));
Which in this case, the sizeof will result in the value 2 being returned.

One of these would perhaps be better.
Code:
file.Write("\n",strlen("\n"));
file.Write("\n",1);

--
 
Yes, a string literal is an array of char in C/C++. Arrays are implicitly converted into pointers to base types in all contexts except sizeof operator arg. Yet another orthogonal (special) case - initializators. They are another story...
So sizeof("\n") == 2 ('\n'+zero terminator)...
 
Hmmm, yes, you're right of course.

Just checked that you're all alert.

:p

/Per

www.perfnurt.se
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top