繁体   English   中英

生成一个随机文件名,然后创建文件,在 C++ 中

[英]Producing a random file name, and then creating the file, In C++

在我的程序中,我试图生成一个随机文件名,然后使用 fopen 创建一个具有该名称的文件。 过程如下

  1. 创建一个随机文件名
  2. 通过尝试在 c:\\ 中创建具有该名称的文件来检查我们是否是管理员
  3. 将东西写入文件

我用来制作随机文件名的函数是:

const char *RandomName(const char *suffix,unsigned int length)
    {
        const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
        int stringLength = sizeof(alphanum) - 1;
        std::string Str;
        unsigned int i;
        Str.append("c:\\");
        for( i = 0; i < length; ++i)
        {
            Str += alphanum[rand() % stringLength];
        }
        Str += suffix;
        const char *str =Str.c_str();
        return str;
    }

我用来创建文件并检查管理员的函数是:

bool IsAdmin()
{
    const char *n = RandomName(".BIN",5);
    cout << n << endl;
    FILE *fp;
    fp = fopen((const char *)n,"w+");
    if (fp == NULL) {
        cout << "File pointer was NULL" << endl;
        return false;
    } else {
        cout << "File pointer is legit" << endl;
        //fclose(fp);
        //remove(n);
        int b;
        for(b = 0; b != 1338; b++)
        {
            char f = 'c';
            fputc(f, fp);
        }
        return true;
    }
}

以管理员身份运行时,程序打印:

c:\9UswA.BIN
Not Admin!

如何让程序创建一个名称与其在屏幕上显示的名称相匹配的文件? 并且没有粗略的行为?

简单只需使用 tmpnam c api

例子:

#include <stdio.h>

  int main(void)
  {
    char name[40];
    int i;

    for(i=0; i<3; i++) {
      tmpnam(name);
      printf("%s ", name);
    }
    return 0;
  }

我认为以管理员身份运行此处创建的 .exe 可以让您创建文件。 不是从任何 IDE 运行程序,而是从文件位置手动运行程序并以管理员身份运行。

为了解决这个问题,我摆脱了的RandomName功能和编辑IsAdmin包括它的代码,有一些调整,我能得到它的工作,至少在某种程度上好,我结束了代码为:

void AdminWrite(const char *suffix,unsigned int length)
{
    FILE *fp;
    const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv";
    int stringLength = sizeof(alphanum) - 1;
    std::string Str;
    unsigned int i;

    Str.append("c:\\Users\\UserName\\Desktop\\");
    for( i = 0; i < length; ++i)
    {
        Str += alphanum[rand() % stringLength];
    }
    Str += suffix;
    const char *str =Str.c_str();
    cout << str << endl;
    fp = fopen(str,"w+");
    if (fp == NULL) {
            cout << "File pointer was NULL" << endl;
            return;
    } else {
        cout << "File pointer is legit" << endl;
        int b;
        for(b = 0; b != 1337; b++)
        {
            char f = 'c';
            fputc(f, fp);
        }
        return;
    }
    return;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM