生成一个随机文件名,然后创建文件,在c++中
Producing a random file name, and then creating the file, In C++
在我的程序中,我试图生成一个随机文件名,然后使用fopen创建一个具有该名称的文件。流程如下
- 创建一个随机文件名
- 检查我们是否是管理员,尝试在c: 中创建一个同名的文件
- 向文件 写入内容
生成随机文件名的函数是:
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将允许您创建该文件。
为了解决这个问题,我去掉了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;
}
相关文章:
- 我如何创建一个列表,然后从中创建两个列表,其中一个用于偶数,另一个用于奇数?
- 如何创建一个C++程序来读取字符串数组中的信息,然后将其排序到类中?
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- C++ 如何创建 2D 数组,将其传递给另一个函数,然后打印
- 在功能中创建一个数组,然后将其返回到main()
- C++ std::vector 创建对象然后添加对象与在向量中创建对象之间的区别?
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- 在构造函数中创建一个字符串数组,然后在主函数中使用它
- 如何在%appdata%中创建文件夹,在其中创建.bat文件,然后执行它?
- 读取该文件,然后创建动态数组
- 创建一个 const unique_ptr然后尝试从它 std::move 会给出与您尝试访问复制构造函数相同的错误
- 如何在C++中创建一个网格,这将允许我将每个索引设置为一个向量,以便以后操作该向量,然后绘制它
- 如何预先分配空类对象,然后在if语句的大括号中创建该对象
- 如果没有数据,则创建一个包含数据的文本文件,然后读取它以检索数据
- 创建指向未符号char []的指针,然后将其传递给SF :: Soundbuffer :: LoadFromememor
- 使用 ros launch 创建一个目录,然后将其路径传递给不同的节点
- 如何在qthread上创建QTCPSERVER,然后从主线程中将其停止
- C++,如何创建和绘制二叉树,然后按预购方式遍历它
- 在函数内部创建一个局部向量,然后将其作为引用传递给其他函数,这些函数将其存储为引用
- 读取文件,然后创建数组函数C++