用C/C编写与操作系统无关的代码++

如何编写一个实用程序,列出目录的所有内容,而不考虑操作系统。 大多数C/C++编译器都定义了可用于检测操作系统的宏。例如,在GCC中,以下是常见的宏。

null
_WIN32 : Defined for both 32 bit and 64 bit windows OS._WIN64 : Defined for 64 bit windows OS.unix, __unix, __unix__ : Defined in UNIX OS__APPLE__, __MACH__ : Defined in Mac OSSource : StackOverflow

在Windows中,我们使用us dir调用列出所有目录,在大多数其他操作系统中使用“ls”。下面是简单的C++实现,列出文件夹的目录,而不考虑OS。

C++

// C++ program to list all directories.
#include <bits/stdc++.h>
using namespace std;
int main()
{
#ifdef _WIN32
system ( "dir" );
#else
system ( "ls" );
#endif
return 0;
}
// This code is contributed SHUBHAMSINGH10.


C

// C program to list all directories.
#include <stdio.h>
int main()
{
#ifdef _WIN32
system ("dir");
#else
system ("ls");
#endif
return 0;
}


上述独立于操作系统的代码与Java的平台独立性完全不同。在Java中,中间字节代码是处理平台依赖关系的非常干净的方式。在这里,我们必须记住特定于编译器的宏,并使用笨拙的#ifdef和#else编写代码,最重要的是,我们需要为每个操作系统重新编译代码。 本文由 Shubham Agrawal 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享