作者:朱金灿
来源:hhttp://blog.youkuaiyun.com/clever101
请看下面一段代码:
#include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> int main( void ) { struct _stat buf; int result; char timebuf[26]; char* filename = "F://MyTest//MyTest//src//TestUnix//stdafx.h"; errno_t err; // Get data associated with "crt_stat.c": result = _stat( filename, &buf ); // Check if statistics are valid: if( result != 0 ) { perror( "Problem getting information" ); switch (errno) { case ENOENT: printf("File %s not found./n", filename); break; case EINVAL: printf("Invalid parameter to _stat./n"); break; default: /* Should never be reached. */ printf("Unexpected error in _stat./n"); } } else { // Output some of the statistics: printf( "File size : %ld/n", buf.st_size ); printf( "Drive : %c:/n", buf.st_dev + 'A' ); err = ctime_s(timebuf, 26, &buf.st_mtime); if (err) { printf("Invalid arguments to ctime_s."); return 1; } printf( "Time modified : %s", timebuf ); } getchar(); return 0; }
熟悉unix或linux平台开发的朋友可能以为它是在unix或linux平台开发的。实际上它是MSDN Library for Visual Studio 2005上的一个例子,可以在VS C++ 2005上成功编译(多字节字符集编译)。
开始我也不太明白为何Windows系统有unix的头文件。最近看了《Windows操作系统原理》才彻底明白了。究其原因,Windows 2000/XP有三种环境子系统:POSIX/UNIX、OS/2和Win32(OS/2只能用于x86系统)。因为有了POSIX/UNIX这个子系统,自然也就有了一个UNIX SDK,所以出现上面的头文件就不足为奇了。事实上微软的发展和unix系统是有一些渊源的:微软历史上曾推出过unix操作系统;windows系统的很多核心开发人员都是资深的unix操作系统的设计和开发人员。
那么这个POSIX/UNIX这个子系统有什么用呢?POSIX代表了UNIX类型的操作系统的国际标准集,它鼓励制造商实现兼容的UNIX风格接口,以使编程者很容易地将他们的应用程序从一个系统移到另一个系统。正因为具有这个特点,很多软件底层(想实现跨平台)、跨平台库喜欢调用UNIX SDK中的函数。我在著名的开源图像库GDAL就见过UNIX SDK中的函数。不过Windows 2000/XP只实现了POSIX.1标准(ISO/IEC 9945-11990或IEEE POSIX 1003.1-1990)。所需的POSIX一致性文档位于Platform SDK中的/HELP目录中。
参考文献:
1. MSDN Library for Visual Studio 2005,Microsoft Corporation
2. 《Windows操作系统原理》,尤晋元 史美林 陈向群 向勇 王雷 马洪兵 郑扣根 马洪兵 编著