zoukankan      html  css  js  c++  java
  • c++程序判断系统是Linux还是Windows

      用C++来实现,本来想了很多,后来越写越烂,而且结果总是不尽人意,干脆这样子好了:

    1 int main() {
    2     int judge = system("cls");
    3     if(judge == 0)     cout << "Windows!" << endl;
    4     else    cout << "Linux!" << endl;
    5     return 0;
    6 }

      只是 linux 下会多了一行东西,如果运行时在背后加个 2>> error 也是可以的,不过好像用户体验还是不好,为了去掉这个,我又想了如何囧办法:

    (感觉好像有点小题大做了,不过确实实现了功能,就不管了,或许以后能用上)

     1 #include <cstdio>
     2 #include <cstdlib>
     3 #include <cstring>
     4 const char *password = "123";
     5 
     6 int main(int argc, char *argv[]) {
     7 
     8     if(argc != 2 || strcmp(argv[1], password) != 0) {
     9         puts("Permission denied!");
    10         return 2;
    11     }
    12     freopen("err", "w", stderr);
    13     FILE *fp = fopen("out", "w");
    14     int judge = system("cls");            // 0 为 Windows,>0 为 Linux
    15     fprintf(fp, "%d
    ", judge == 0 ? 0 : 1);
    16     fclose(fp);
    17     return 0; 
    18 }
    create.cpp
     1 #include <cstdio>
     2 #include <cstdlib>
     3 #include <cstring>
     4 const char *password = "123";
     5 
     6 int main(int argc, char *argv[]) {
     7 
     8     if(argc != 2 || strcmp(argv[1], password) != 0) {
     9         puts("Permission denied!");
    10         return -1;
    11     }
    12     
    13     char cmd[20] = "create ";
    14     system(strcat(cmd, password));
    15     FILE *fp = fopen("out", "r");
    16     int judge;
    17     fscanf(fp, "%d", &judge);
    18     fclose(fp);
    19 
    20     if(judge == 0) {
    21         system("del out");
    22         system("del err");
    23         return 0;
    24     }
    25     else if(judge > 0) {
    26         system("rm -f out");
    27         system("rm -f err");
    28         return 1;
    29     }
    30     else    return -1;
    31 }
    getSystem.cpp
     1 #include <cstdio>
     2 #include <cstdlib>
     3 #include <cstring>
     4 
     5 inline int getSystem() {
     6     return system("getSystem 123");
     7 }
     8 
     9 int main() {
    10     
    11     int res = getSystem();
    12     
    13     if(res == 0)    puts("Windows");
    14     else    puts("Linux");
    15     
    16     return 0;
    17 }
    main.cpp

      都编译好后运行 main.exe 或者 main.out 就行,另两个.exe 已加密(密码可以自行更改),这样子直接就可以避免直接点击运行他们。

  • 相关阅读:
    [转]SQL Server中的执行引擎入门
    [转]C# 导入导出Excel通用类(SamWang)
    【转】TSQL查询进阶—理解SQL Server中的锁
    [转载]使用分页方式读取超大文件的性能试验
    【总结】读《WEB三层架构的束缚》后的感想
    【转】jQuery使用 $.post提交json数据
    【原创】关于索引的总结
    【转】.net 匿名函数的变化
    【转】List<T>的Sort,Find,Exists等的使用
    【转】Http中Get/Post请求区别
  • 原文地址:https://www.cnblogs.com/Newdawn/p/5054409.html
Copyright © 2011-2022 走看看