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

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

本文关键字:创建 然后 文件 c++ 文件名 随机 一个      更新时间:2023-10-16

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

  1. 创建一个随机文件名
  2. 检查我们是否是管理员,尝试在c:
  3. 中创建一个同名的文件
  4. 向文件
  5. 写入内容

生成随机文件名的函数是:

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;
    }
我用来创建文件并检查Admin的函数是:
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;
    }
}

当以Admin身份运行时,程序打印:

<>之前c: 9 uswa.bin不是管理员!之前

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

很简单只需使用tmpnamc 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中运行程序,而是手动从文件位置以admin身份运行。

为了解决这个问题,我去掉了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;
}
相关文章: