WriteFile need help,

Can some one explaint to me why is my output file print out garbage string, 
event I print BOM at the begining of the file? Did I miss something?

output.txt
⁥Tue Feb 07 15:22:02 2006⁢  Testing log file 1.

///////////MY CODE////////////////////
WORD BOM=0xfeff; 
DWORD cBytes;

hFile = CreateFile(szDirectory, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, 
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
if (NULL != hFile && INVALID_HANDLE_VALUE != hFile)
{
   SetFilePointer(hFile, 0, NULL, FILE_BEGIN); 
  WriteFile(hFile, &BOM, sizeof(BOM), &cBytes, NULL); 
}


void WriteToFile(wchar_t* p_Data, HANDLE hFile) 
{
  time_t ltime;
  wchar_t dwBuffer [512];
  DWORD dwNumWritten, dwLen;
  struct tm * timeinfo;

  time( &ltime );
  timeinfo = localtime(&ltime);
  swprintf(dwBuffer, L"%s\t%s\r\n", _wasctime(timeinfo), p_Data);
  if (hFile != INVALID_HANDLE_VALUE)
  {
      dwLen = (wcslen(dwBuffer) + 1) * sizeof(wchar_t);
      WriteFile(hFile, (LPVOID)dwBuffer, dwLen, &dwNumWritten,NULL);
  }
  LocalFree(dwBuffer);
}

0
ttan (17)
2/7/2006 10:59:10 PM
vc.mfc 33608 articles. 0 followers. Follow

3 Replies
664 Views

Similar Articles

[PageSpeed] 30

"ttan" <ttan@discussions.microsoft.com> schrieb im Newsbeitrag 
news:7FC9F61B-D7A0-45D3-B246-3148D61044C3@microsoft.com...
> Can some one explaint to me why is my output file print out garbage 
> string,
> event I print BOM at the begining of the file? Did I miss something?
>
> output.txt?
> ??Tue Feb 07 15:22:02 2006?  Testing log file 1.
>
> ///////////MY CODE////////////////////
> WORD BOM=0xfeff;
> DWORD cBytes;
>
> hFile = CreateFile(szDirectory, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
> CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
> if (NULL != hFile && INVALID_HANDLE_VALUE != hFile)

CreateFile returns INVALID_HANDLE_VALUE on error. 0 is a perfectly legal 
file handle. Testing the handle against 0 might report errors that are no 
errors at all.

> {
>   SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
>  WriteFile(hFile, &BOM, sizeof(BOM), &cBytes, NULL);
> }
>
>
> void WriteToFile(wchar_t* p_Data, HANDLE hFile)
> {
>  time_t ltime;
>  wchar_t dwBuffer [512];
>  DWORD dwNumWritten, dwLen;
>  struct tm * timeinfo;
>
>  time( &ltime );
>  timeinfo = localtime(&ltime);
>  swprintf(dwBuffer, L"%s\t%s\r\n", _wasctime(timeinfo), p_Data);

_wasctime returns a string ending with LF only. When written to a text file 
using fprintf or operator<< a single LF is translated into CR/LF. This 
conversion is not performed if you open a file using CreateFile and it would 
be not a good idea to open a unicode file in text mode. I guess that then LF 
would be translated into two chars with values of 0x0D and 0x0A instead of 
two wchar_ts with values of 0x000D and 0x000A. You should not write that 
last character but add your own code to write a complete end of line 
sequence. And while you are fixing your program, you should stop copying a 
string of unknown length into a fixed size buffer. More appropriate code to 
output a timestamp and a message can be something like

    wchar_t const* timestamp = _wasctime(timeinfo);
    WriteFile(hFile, timestamp, sizeof(wchar_t) * (wcslen(timestamp) - 1), 
&dwNumWritten, 0);
    WriteFile(hFile, L"\t", sizeof(wchar_t), &dwNumWritten, 0);
    WriteFile(hFile, p_Data, sizeof(wchar_t) * wcslen(p_Data), 
&dwNumWritten, 0);
    WriteFile(hFile, L"\r\n", 2 * sizeof(wchar_t), &dwNumWritten, 0);

>  if (hFile != INVALID_HANDLE_VALUE)
>  {
>      dwLen = (wcslen(dwBuffer) + 1) * sizeof(wchar_t);
>      WriteFile(hFile, (LPVOID)dwBuffer, dwLen, &dwNumWritten,NULL);
>  }
>  LocalFree(dwBuffer);

What is this supposed to do? dwBuffer is an automatic variable allocated on 
the program's stack. Such variables should never be explicitly freed. This 
will be done automatically when the scope containing such variables is left.

> }

HTH
    Heinz 


0
hozwirk.SPAM (112)
2/7/2006 11:56:10 PM
What's the LocalFree at the end for?  Isn't dwBuffer an array on the stack? Are you corrupting 
memory before the file buffer is flushed?

"ttan" <ttan@discussions.microsoft.com> wrote in message 
news:7FC9F61B-D7A0-45D3-B246-3148D61044C3@microsoft.com...
> Can some one explaint to me why is my output file print out garbage string,
> event I print BOM at the begining of the file? Did I miss something?
>
> output.txt?
> ??Tue Feb 07 15:22:02 2006?  Testing log file 1.
>
> ///////////MY CODE////////////////////
> WORD BOM=0xfeff;
> DWORD cBytes;
>
> hFile = CreateFile(szDirectory, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
> CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
> if (NULL != hFile && INVALID_HANDLE_VALUE != hFile)
> {
>   SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
>  WriteFile(hFile, &BOM, sizeof(BOM), &cBytes, NULL);
> }
>
>
> void WriteToFile(wchar_t* p_Data, HANDLE hFile)
> {
>  time_t ltime;
>  wchar_t dwBuffer [512];
>  DWORD dwNumWritten, dwLen;
>  struct tm * timeinfo;
>
>  time( &ltime );
>  timeinfo = localtime(&ltime);
>  swprintf(dwBuffer, L"%s\t%s\r\n", _wasctime(timeinfo), p_Data);
>  if (hFile != INVALID_HANDLE_VALUE)
>  {
>      dwLen = (wcslen(dwBuffer) + 1) * sizeof(wchar_t);
>      WriteFile(hFile, (LPVOID)dwBuffer, dwLen, &dwNumWritten,NULL);
>  }
>  LocalFree(dwBuffer);
> }
> 


0
ScotB (233)
2/8/2006 3:47:40 AM
See below...
On Tue, 7 Feb 2006 14:59:10 -0800, "ttan" <ttan@discussions.microsoft.com> wrote:

>Can some one explaint to me why is my output file print out garbage string, 
>event I print BOM at the begining of the file? Did I miss something?
>
>output.txt?
>??Tue Feb 07 15:22:02 2006?  Testing log file 1.
>
>///////////MY CODE////////////////////
>WORD BOM=0xfeff; 
>DWORD cBytes;
>
>hFile = CreateFile(szDirectory, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, 
>CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
>if (NULL != hFile && INVALID_HANDLE_VALUE != hFile)
>{
>   SetFilePointer(hFile, 0, NULL, FILE_BEGIN); 
>  WriteFile(hFile, &BOM, sizeof(BOM), &cBytes, NULL); 
>}
>
****
Since you did CREATE_NEW, the file will be created, and the file pointer will by
definition be at the start of the file, so the SetFilePointer is redundant.  Also, testing
for NULL is erroneous.  Note that CREATE_NEW requires that the file not already exist; is
that really what you want?  CREATE_ALWAYS will replace the existing file, in which case
the  file contents will be replaced, and again the SetFilePointer is wrong.
*****
>
>void WriteToFile(wchar_t* p_Data, HANDLE hFile) 
>{
>  time_t ltime;
>  wchar_t dwBuffer [512];
****
Are you using VS6 or VS.NET?  If VS.NET, you could use a CStringW, and do a .Format method
instead of using a fixed allocation on the stack, e.g.,

	CStringW buffer;
****
>  DWORD dwNumWritten, dwLen;
>  struct tm * timeinfo;
>
>  time( &ltime );
>  timeinfo = localtime(&ltime);
****
You could then replace the statement below with
	buffer.Format(L"%s\t%s\r\n", _wasctime(timeinfo), p_Data);
****
>  swprintf(dwBuffer, L"%s\t%s\r\n", _wasctime(timeinfo), p_Data);
>  if (hFile != INVALID_HANDLE_VALUE)
>  {
>      dwLen = (wcslen(dwBuffer) + 1) * sizeof(wchar_t);
****
Note that this writes the terminating NUL character; is that what you intended?
****
>      WriteFile(hFile, (LPVOID)dwBuffer, dwLen, &dwNumWritten,NULL);
>  }
>  LocalFree(dwBuffer);
****
Since you didn't allocate (and LocalAlloc would be a bad idea anyway), you don't need to
LocalFree
****
>}
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15974)
2/13/2006 5:07:34 AM
Reply:

Similar Artilces:

Odd chart type needed
I need a chart type that does not seem to be available in Excel 2007 or 2003. I'm graphing a gamma ray emission spectrum. The x-axis is photon energy. The y-axis is number of gamma rays per second The plot requires vertical LINES at the energy of each gamma ray. The height of the line is the number of gamma rays. The x position of each line is its energy. The chart COULD be a vertical bar chart with very narrow bars. But Excel won't allow bars that thin, and needs them equally spaced. Is there a way to create such a vertical line plot in Excel 2007 (or 2003)? On Apr 13, 12:30=A0pm,...

DSum help
Being new to vba and Access, I think what I am trying to do is out of my realm of understanding. I have two querries that query the same table "QtyUsed". One query "QtyUsed6Mo" filters results by the date field to records within the last 6 months. The other "QtyUsedYr" filters within the last year. I want to create a DSum that will add all the records in the query that have the same "NSN" and add the qty "Used" to another table "DataTable.QtyUsed6Mo and DataTable.QtyUsedYr" Bobby, Usually it is not good practice to store these calcul...

Need to undo sync mess
Hi All, I just picked up responsibility for an SBS WS03 server. The customer has a Vista desktop. The customer can not delete anything from his My Documents as they all have green circles on them, meaning they need to sync. The customer wants a plain old put my My Documents on the server. Has no idea how Sync got turned on in the first place. How do I turn sync off and get all his My Documents back on the server where they belong? I can not figure out who is doing what to who. :'[ Many thanks, -T Maybe some help here... Working with network files when you are...

Need site for VB Tutorial
Hello Can someone suggest some site to learn VB?? Thanks Tom -- SMIL ----------------------------------------------------------------------- SMILE's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=488 View this thread: http://www.excelforum.com/showthread.php?threadid=26676 Hi see: http://www.mvps.org/dmcritchie/excel/getstarted.htm -- Regards Frank Kabel Frankfurt, Germany "SMILE" <SMILE.1dp2ta@excelforum-nospam.com> schrieb im Newsbeitrag news:SMILE.1dp2ta@excelforum-nospam.com... > > Hello > Can someone suggest some site to learn VB...

Help Required
I need a little help while working of MS Access 2000. I have a table which contians two columns labellbed as A and B. In column A I can either enter Vegetable or Fruit (combo box). Now what I want is that if I select Vegetable in Column A list of Vegetables appear in colum B and vice versa. I have tried to write queries and have tried other methods too but I haven't been successful. I will be very thankful if someone can help me in this regard. Kind Regards, Hasnain Raja What you are asking is a very common question called a cascading combo. NOTE: DON'T EVER USE TABLES FOR ENTER...

DGView Binding (Really need help on this one, please!)
I've posted this issue a couple of days ago, but I wasn't clear, so I'm trying again. I want to be able to bind a collection of "Rows" to a DataGridView para the public fields aren't fixed. If each "row" was made out of fixed public fields I know I could easily achieve this using BindingList. My class structure is as follows: I have a Field that exposes Name and Value attributes. Now, I also have a class Fields which is basically a collection of class Field as you can see: Fields : KeyedCollection<string, Field>. So far everything ...

HELP PLEASE
This is a multi-part message in MIME format. ------=_NextPart_000_001B_01CB33C4.88E3D3F0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Does anyone know how to get the animated sigtags moving on windows 7 = when I=20 put them on my e-mail they just stop still would appreciate any help Thanks ------=_NextPart_000_001B_01CB33C4.88E3D3F0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HT...

ENTREPRENEURS NEEDED
Are you a serious Entrepreneur in search of a business that has fabulous growth capabilities? The Wellness Business is the next great business movement. Would you like a proper exchange of values, value given for value received. Do your research on this Company and its exploding U.S. and International Expansion. See why our exclusive products, truly helps people. www.pk.enliveninternational.com Our optional marketing tool, Plug and Play, works 24hrs a day, 7 days a week for you. Take a tour and see how this automated e-mail system can help you expand pass your local area www.p...

Need to integrate a check and witholdings
Hello all. I need to create an integration that I have a customer id, check date, check number, Check Amt, Witholding Amt and Adj Total Due Amt. I know I have done this before but it has been a long while. What Destination do I use for this "Cash Receipt"? and then how do I handle the witholdings (taken rings a bell not sure if that is correct) etc. Thanks all for any advice to get started. ...

Help Me Please!!!
I used this forum back in May this year to find out how to make a drop down list on which i can click on the name and it takes me straight to that worksheet. This is working fine but i know need to add more names to the list. I think i was given a formula to out in somewhere but i cannot remember what it was or how to view Can Someone Help me please!! :) -- beng120 ------------------------------------------------------------------------ beng120's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=23188 View this thread: http://www.excelforum.com/showthread.php?thr...

cannot access online help in excel
online help works in all office 2003 programs except excel ...

need some pointers
First, i'm sorry for not doing the usual things like scouring the annals of this group and lurking a long time before posting. I need some guidance and the sooner the better. What i want to build is basically a database. I need the names of all of the staff members i need to help train. I need the plan of action for each staff member. I need the dates, types and lengths of the trainings completed. I need to total the training times, with the possibility to separate the different types of training and total them also. I need an easy to read front page, with the ability to select any or a...

WriteFile
Hi , I am using WriteFile function for writting some data to harddisk. Is there any limit in size of data it can write. Basically this function is writting imcomplete data. I checked the contents of file. ( Writs encoded data to file then decode the data using Winzip ( MIME data ) no of Bytes are at boundries like : fff, 9fff, ffff ... Any idea why this is hapening ? I'm not sure if there is a limit, or how to find out. Are you checking the parameter that tells the number of bytes written to see if it equals the number of bytes to write? Perhaps you can just keep calling WriteFile...

VLookup in VBA Help Needed
I am getting an "Unable to get VLookup property of WorksheetFunction class" error on line "c.Offset(0, -1) =", even though VendorTable Referto:=AAV_Table!$B$2:$C$1260 Private Sub cmdUpdate_Click() Dim c As Range Dim lRow As Long Worksheets("MarketList").Activate lRow = ActiveSheet.UsedRange.Rows.Count For Each c In Worksheets("MarketList").Range("C2:C" & lRow).Cells c.Offset(0, -1) = Application.WorksheetFunction.VLookup(c, VendorTable,2,False) Next c End Sub VendorTable defined here: Worksheets("AAV_Table&quo...

do people need to be out of GP for the backup
Hello: I was surprised to find out just now that, unlike with making a manual backup of a SQL company database, you cannot use the GP 9.0 File...Backup utility to backup a company if users are in that company. (SQL manual backups DO let you make such backups, even if people are in the company.) Now, let's say that you want to take advantage of the Schedule feature of the GP backup window. Moreover, let's say that users are still logged into GP while the scheduled backup is running. A "regular" SQL database backup plan will allow a backup to be performed even if use...

Internet site shortcut needed.
How do I put an internet site on the screen as a shortcut. Seems difficult. Frank "Frank Martin" <fm@general.com.au> wrote in message news:%23XQkp1UpKHA.1548@TK2MSFTNGP02.phx.gbl... > How do I put an internet site on the screen as a shortcut. Seems > difficult. > > Frank > Save it as a Favorite. Drag it from My Favorites to the Taskbar and then to the Desktop if you want. -- Bruce Hagen MS-MVP [Mail] Imperial Beach, CA And, or: show the menu bar>File>Send>Shortcut to Desktop >WT< ...

occasionally changing tables
I have a database that requires fields to be added to tables and/or new tables to be added 1-5 times per month. One of my forms is for new entries, another form is to edit older entries, and a couple of other forms only show filtered data (which is filtered via queries). Every time I make a change to an existing table or add a new table, I have to update every single form. Almost all of the forms look exactly alike, they are just connected to different queries. The new info also has to be added to every query. Is there an easier to may to make changes? Can the forms and queries be base...

Range.Select Using Variables
Dim firstrowOLD As Long Dim lastrowOLD As Long Cells.Find(What:="Text1", -etc-) firstrowOLD = ActiveCell.Row Cells.Find(What:="Text2", -etc-) lastrowOLD = ActiveCell.Row -need correct syntax for next line- Range("H" & firstrowOLD : "I" & lastrowOLD).Select -I get a Compile error: Expected List Seperator at the colon- -not sure how this is different from Range("H25:I30").Select- -- gradientS ------------------------------------------------------------------------ gradientS's Profile: http://www.excelforum.com/member.php?a...

Please Help with Free/Busy
I am trying to setup a free/busy server and need help. I have got an account setup with ftp and http servers running. I can publish .vfb file to the server with ftp, but am having a problem when trying to search others file. I got it to work with a file: share, but I need ftp or http. Please help if you can. Thanks, Steve ...

need Outlook!
Anybody: I had to uninstall Outlook from the MS Office XP suite because it caused a problem with my printer. Is there a way I can get the installation files for Outlook by itself to re-add to the suite? My setup CD is corrupted. Please! Any assistance will be greatly appreciated! No, you'll need the CD. You can contact Microsoft to obtain a replacement set of CD's. -- Robert Sparnaaij [MVP-Outlook] www.howto-outlook.com Tips of the month: -What do the Outlook Icons Mean? -Create an Office 2003 CD slipstreamed with Service Pack 1 ----- "Paul J. Perillo" <vze47j...

Urgent!Need help with creating a Christmas PowerPoint slideshow
I'm creating a Christmas PowerPoint slide show of my family,can someone tell me where I can download free Christmas templates for my presentation? And I want to put this PowerPoint slideshow on Youtube to share with all my relatives and friends. I tried to upload an.PPT file to Youtube but failed, any idea? Thanks Dwight, There are some templates on office online: http://office.microsoft.com/en-us/templates/results.aspx?qu=CHRISTMAS&sc=4&av=ZPP -- Luc Sanders MVP - PowerPoint "Dwight" <Dwight@discussions.microsoft.com> schreef in bericht new...

Need a formula #4
I would like to have a formula that would calculate the following. Starting in year 2007 and ending in 2024 if each year the amount went up by 3 % each year My worksheet will have the years in column A and I would like the calculations to show up in column B Thank you to anyone willing to create this formula for me If you have the years in A2:A19 and in B2 you have the start amount, in B3 enter =B2*1.03 and copy down to B19 -- HTH Nick Hodge Microsoft MVP - Excel Southampton, England nick_hodgeTAKETHISOUT@zen.co.ukANDTHIS www.nickhodge.co.uk "Just Me" <No@isp.com&...

Help with average formula
Hi, I'm trying to calculate average of figures as follows: 1.1.2003 10 2.1.2003 20 3.1.2003 15 4.1.2003 5.1.2003 5 So the question is that if there is one row that has no numbers in it how do I exclude it from the average... meaning that average would b counted like this (10+20+15+5)/4 and not (10+20+15+5)/5. Thanks //juh -- Message posted from http://www.ExcelForum.com Juha If a cell is blank, it won't be included in the average. Andy. "Juha" <Juha.ybp1y@excelforum-nospam.com> wrote in message news:Juha.ybp1y@excelforum-nospam.com... > Hi, > > I...

Chart percentage display needs to be neater
When using line charts with percentages at various intervals, the resulting chart usually has the percentages displayed over the trendline and I end up having to click each percentage and move them so they can be more easily seen on the chart. Is there a way to automate this either at the time I run the chart or once created? Thanks. You could select the set of labels, press CTRL+1 (numeral one) to open the Format Data Labels dialog, and on the Alignment tab, choose the Above or Below position option, instead of the default Left. - Jon ------- Jon Peltier, Peltier Technical Services,...

Install Module choices mapped to Help Menu Module Listing
Hello, when installing GPv10 you have choices of what to install. For example: EFT for Receivables, Electronic Bank Reconciliation, Professional Services Tools Library, etc. But when you go under Help>Options and display the registration report it's not a one-to-one mapping of what you chose when doing the install. For example modules listed in my registration report that are not registered are Cashbook Bank Management, Bank One Commercial Card Integration, Bank One Direct Paycheck Card Integration. I don't know if these are mapped to EFT for Receivables or Electronic Bank Recon...