Windows和Linux下的文件访问和删除
Windows和Linux下的文件操作。系统内核不同,所使用的头文件和API也不同。按照宏定义,编写兼容Windows和Linux系统的程序,实现无缝切换。
1. 头文件介绍
文件操作所必须的头文件: Windows: io.h ,Linux: unistd.h 。
以文件的检测为例,具体解析。
Windows下是io.h中的_access方法:
#define _A_NORMAL 0x00 /* Normal file - No read/write restrictions */
#define _A_RDONLY 0x01 /* Read only file */
#define _A_HIDDEN 0x02 /* Hidden file */
#define _A_SYSTEM 0x04 /* System file */
#define _A_SUBDIR 0x10 /* Subdirectory */
#define _A_ARCH 0x20 /* Archive file */
// ...
_Check_return_ _CRTIMP int __cdecl _access(_In_z_ const char * _Filename, _In_ int _AccessMode);
Linux下是unistd.h中的access方法:
/* Values for the second argument to access.
These may be OR'd together. */
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
#define X_OK 1 /* Test for execute permission. */
#define F_OK 0 /* Test for existence. */
/* Test for access to NAME using the real UID and real GID. */
extern int access (const char *__name, int __type) __THROW __nonnull ((1));
2. 兼容方式
宏定义参数:_WIN32、_WIN64分别代表Windows系统的32位和64位。
通过判定以上两个宏,可以分别对不同系统下,指定不同的头文件和API。
#if defined(_WIN32) || defined(_WIN64)
// Windows header
// Windows API
#else
// Linux header
// Linux API
#endif
3. 文件操作API
(1)Windows: stdio.h、io.h
文件访问: _access
文件删除: remove
(2)Linux: stdio.h、unistd.h
文件访问: access
文件删除: remove
4. 实测案例
#if defined(_WIN32) || defined(_WIN64)
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <io.h>
#else
#include <unistd.h>
#endif
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/* Delcarations. */
char testPath[256] = { 0 };
/* Function: main
*/
int main(int argc, char* argv[])
{
// 输入参数捕获。
if (2 == argc)
{
strcpy(testPath, argv[1]);
}
else{
#if defined(_WIN32) || defined(_WIN64)
strcpy(testPath, "D:\\TRS-done.log");
fprintf(stderr, " Using default parameters !! \n");
#else
fprintf(stderr, " Error with parameters !! \n");
return -1;
#endif
}
// 访问。
int ret = -1;
#if defined(_WIN32) || defined(_WIN64)
ret = _access(testPath, _A_NORMAL);
#else
ret = access(testPath, F_OK);
#endif
if (0 > ret)
{
fprintf(stderr, "No file ~ \n");
}
else
{// 删除。
ret = remove(testPath);
if (0 > ret)
{
fprintf(stderr, "Failed to remove the file ! \n");
}
else
{
fprintf(stderr, "Success to remove the file ~ \n");
}
}
//
getchar();
//
return 1;
}