api一日一练 第10天 课后思考题 (点评版)赠送 Delphi版+汇编版本
废话:"api编程其实很好玩的哦。希望初学者先看C语言"
小七其实一直在使用C++,他误认为自己用的是C语言
C语言和C++区别很大,而且有些问题导致C和C++程序员决裂
建议大家用C语言就用标准的C语言,不要混杂C++却以为自己用的是C
C++有许多特性和C语言是不一样的.特别是参数传递!
切记切记!千万不要混在一起认为是一样的.
既然扩大10M就可以直接申请1M循环10次即可,
内存操作速度远比硬盘要快得多,所以硬盘最好尽量少操作,
一次性写入大数据即可(1M刚好,其实16M以下都可以)
Delphi版本:
program Sdk10;
uses
Windows;
var
hFile: THandle;
dwBytes: DWORD;
nLoop: DWORD;
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;
lpszStr := Pointer(GlobalAlloc(GPTR, 1024));
if (lpszStr = nil) then
begin
CloseHandle(hFile);
Exit;
end;
SetFilePointer(hFile, 0, nil, FILE_END); //指向的文件字符的位置。这里是指向末尾
// 以下循环进行了优化.原版太复杂而且不便于理解(而且++计数器是错的)
nLoop := 1024 * 10;
while (nLoop > 0) do
begin
WriteFile(hFile, lpszStr^, 1024, dwBytes, nil);
Dec(nLoop);
end;
CloseHandle(hFile);
GlobalFree(HGLOBAL(lpszStr));
if (MessageBox(0, '是否打开文件测试下运行正常?', 'xqmsyk.com',
MB_YESNO or MB_ICONQUESTION) = IDYES) then
begin
WinExec('c:\1.exe', SW_SHOW);
MessageBox(0, '文件增大成功,是不是特别简单?', 'xqmsyk.com', 0);
end;
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
szTextQuestion db "是否打开文件测试下运行正常?", 0
szText db "文件增大成功,是不是特别简单?", 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
; 1024其实这里完全可以直接申请到1M然后循环写入10次
invoke GlobalAlloc, GPTR, 1024
.if (!eax)
invoke CloseHandle, @hFile
ret
.endif
mov @lpszStr, eax
invoke SetFilePointer, @hFile, 0, NULL, FILE_END
; API调用会破坏ecx平衡,先保存ecx
mov ecx, (1024 * 10)
@@:
push ecx
invoke WriteFile, @hFile, @lpszStr, 1024, addr @dwBytes, NULL
pop ecx
loop @B
invoke CloseHandle, @hFile
invoke GlobalFree, @lpszStr
invoke MessageBox, 0, offset szTextQuestion, offset szCaption, MB_YESNO or MB_ICONQUESTION
.if (eax == IDYES)
invoke WinExec, offset szFile, SW_SHOW
invoke MessageBox, 0, offset szText, offset szCaption, 0
.endif
ret
WinMain endp
start:
invoke WinMain
ret
end start
楼主说的对,,,要严格要求自己。。。。。。。
页:
[1]