api一日一练 第10天 (点评版)赠送 Delphi版+汇编版本
废话:首先我想说.15字节就用不着动态申请内存空间了.
代码中有不少错误
1.char buf="xqmsyk.com";--这绝对是一个不正轨的写法
lstrcpy(buf, "xqmsyk.com");应该这样写.
或者直接char *buf = "xqmsyk.com";都比这样静态赋值要高效
2.new char ---没有把字符串结尾算进去应该是申请16字节才对
3.释放动态数组请使用 delete[] string;这样的写法
4.new完了没有判断(如果new失败了会返回NULL,这样写数据肯定会崩溃!)
以上三条千万要注意,不要出现此类错误!
Delphi版本:
program Sdk10;
uses
Windows;
var
hFile: THandle;
dwBytes: DWORD;
szBuf: Array Of Char;
lpszStr: PChar;
begin
hFile := CreateFile('c:\1.exe', GENERIC_WRITE, FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile = INVALID_HANDLE_VALUE) then
begin
MessageBox(0, '文件不存在或者无法打开', 'xqmsyk.com', 0);
Exit;
end;
lstrcpy(szBuf, 'xqmsyk.com'); //15字符
SetFilePointer(hFile, 0, nil, FILE_END); //指向的文件字符的位置。这里是指向末尾
WriteFile(hFile, szBuf, 15, dwBytes, nil);//写入字符串 xqmsyk.com
lpszStr := Pointer(GlobalAlloc(GPTR, 15));
if (lpszStr = nil) then
begin
CloseHandle(hFile);
Exit;
end;
SetFilePointer(hFile, -15, nil, FILE_END);//指向的文件字符的位置。这里很关键,把指针指向回写入的那个字符头上
ReadFile(hFile, lpszStr^, 15, dwBytes, nil);//读取刚刚写入的字符串
CloseHandle(hFile);
MessageBox(0, lpszStr, 'xqmsyk.com', 0);
GlobalFree(HGLOBAL(lpszStr)); //动态申请的内存释放
end.
汇编版本:
.686
.model flat, stdcall
option casemap:none
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\user32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\user32.lib
.data
szFile db "c:\1.exe", 0
szError db "文件不存在或者无法打开", 0
szFmt db "Size:字节 %d-->xqmsyk.com", 0
szCaption db "xqmsyk.com", 0
.code
WinMain proc
LOCAL @hFile: DWORD
LOCAL @dwFileSize, @dwBytes: DWORD
LOCAL @szBuf: BYTE
LOCAL @lpszStr: DWORD
invoke CreateFile, offset szFile, GENERIC_WRITE, FILE_SHARE_WRITE, \
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0
.if (eax == INVALID_HANDLE_VALUE)
invoke MessageBox, 0, offset szError, offset szCaption, 0
ret
.endif
mov @hFile, eax
invoke lstrcpy, addr @szBuf, offset szCaption
invoke SetFilePointer, @hFile, 0, NULL, FILE_END
invoke WriteFile, @hFile, addr @szBuf, 15, addr @dwBytes, NULL
; 16字节
invoke GlobalAlloc, GPTR, 16
.if (!eax)
invoke CloseHandle, @hFile
ret
.endif
mov @lpszStr, eax
; 个人觉得直接设置成文件起始不是更好么?
invoke SetFilePointer, @hFile, 0, NULL, FILE_BEGIN
invoke ReadFile, @hFile, @lpszStr, 15, addr @dwBytes, NULL
invoke CloseHandle, @hFile
invoke MessageBox, 0, @lpszStr, offset szCaption, 0
invoke GlobalFree, @lpszStr
ret
WinMain endp
start:
invoke WinMain
ret
end start
感谢楼主的补充改正。。。。{:1_1:}
页:
[1]