文章内容
之前写的一点windows下编程的内容,每一篇都会设立几个目标(题目来自国外某大学),并写一个可运行的实例出来用于熟悉各种API,并把相关的API的官方MSDN文档附上,大伙可自行参考学习相关API用法
目标
原版
You should implement a function, which performs the following actions:
- Create two new directories in the current working directory named Dir_1 and Dir_2 (CreateDirectory).
- Create an array of 10 elements of DWORD type. Fill in the array as follows: the value of each i-th element is equal to i*i.
- In the Dir_1 directory, create a file named test.bin (CreateFile). When launching the application, if a file with the same name already exists, then it must be overwritten (CREATE_ALWAYS).
- Write an array of 10 elements of the DWORD type (WriteFile) created in step 2 to the file.
- Write to the end of the file a string of TCHAR elements with the following content:
TCHAR str[] = TEXT(“Hello, World!”);
To calculate the length of a string in characters, use the _tcslen function from the <tchar.h> header file. - Get the size of the test.bin file (GetFileSize) and display it on the screen.
- Close the handle of the test.bin file (CloseHandle).
- Copy the test.bin file from the Dir_1 directory to the Dir_2 directory (CopyFile). If the file is named test.bin already exists in the Dir_2, then it must be overwritten.
翻译版本
- 在当前工作目录中创建两个名为Dir_1和Dir_2的新目录(CreateDirectory)。
- 创建一个包含10个DWORD类型元素的数组。按如下方式填充数组:每个第i个元素的值等于i*i。
- 在Dir_1目录中,创建名为test.bin(CreateFile)的文件。启动应用程序时,如果已存在同名文件,则必须覆盖该文件(CREATE_ALWAYS)。
- 将步骤2中创建的DWORD类型(WriteFile)的10个元素数组写入文件。
- 在文件末尾写入一个TCHAR元素字符串,内容如下:
TCHAR str[] = TEXT(“Hello, World!”);
要计算字符串的字符长度,请使用<tchar.h>头文件中的_tcslen函数。 - 获取test.bin文件的大小(GetFileSize)并将其显示在屏幕上。
- 关闭test.bin文件的句(CloseHandle)。
- 将test.bin文件从Dir_1目录复制到Dir_2目录(CopyFile)。如果名为test.bin的文件已存在于Dir_2中,则必须覆盖该文件。
编译器
visual studio2013 ,不同版本有细微差异,不过都是小修即可完整运行
代码
#include<iostream>
#include<windows.h>
#include<tchar.h>
using namespace std;
void task_two_part_one() {
CreateDirectoryA(".\\Dir_1", nullptr);
CreateDirectoryA(".\\Dir_2", nullptr);
DWORD p[10];
for (int i = 0; i < 10; ++i) {
p[i] = (i + 1) * (i + 1);
}
HANDLE f = CreateFileA(".\\Dir_1\\test.bin", GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
nullptr);
WriteFile(f, p, 10 * sizeof(DWORD), 0, nullptr);
TCHAR str[] = TEXT("Hello,World!");
WriteFile(f, str, _tcslen(str), 0, nullptr);
cout << GetFileSize(f, nullptr) << endl;
CloseHandle(f);
CopyFileA(".\\Dir_1\\test.bin", ".\\Dir_2\\test.bin", FALSE);
};
int main() {
task_two_part_one();
}
解释
CreateDirectoryA
CreateFileA
WriteFile
_tcslen
GetFileSize
CloseHandle
CopyFile