我有点像这个人 (coava) 发布的类似问题。
( Append Random Text without Repetition for File (C) )
总结:基本上我正在尝试创建文件,将随机单词附加到其中并将文件存储到目录中
我已经尝试了给出的解决方案,但它对我不起作用,可能是因为在我的情况下我也将这些文件存储在目录中。
所以我的代码(编辑:这是我的代码的一部分)看起来像这样:
char *room[4];
room[0] = "okay";
room[1] = "sure";
room[2] = "fine";
room[3] = "noo";
int pid = getpid();
char dirname[30]
sprintf(dirname,"rooms.%d",(int)getpid());
mkdir(dirname,0777);
int bufSize=128;
char *current = malloc(bufSize);
int nroom = sizeof(room) - 1;
int count;
for (count=0;count<3;count++) {
int ipick = rand()%nroom;
int *pick = room[ipick];
room[nroom] = room [--nroom];
snprintf(currentFile,bufSize,"file-%d.txt",count);
FILE *f = fopen(currentFile,"w")
fprintf(f, "YOUR ROOM: %s\n",pick);
fclose(f);
}
然后出现seg.fault,我尝试修改
snprintf(currentFile,bufSize,"file-%d.txt",count);
进入
snprintf(currentFile,bufSize,"file-%d.txt",dirname,count);
它没有给出 seg.fault,但它只是在目录外打印,并在每个文件内部添加 有时我得到随机值,如
“连接主机:@blablabla”或一些垃圾符号。
我的 for 循环有问题吗?还是在其他地方?
此代码有效:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void)
{
char *room[4] = { "okay", "sure", "fine", "noo" };
int pid = getpid();
char dirname[30];
sprintf(dirname, "rooms.%d", pid);
if (mkdir(dirname, 0777) != 0)
{
fprintf(stderr, "Oops: did not create directory %s\n", dirname);
exit(1);
}
int bufSize = 128;
char *current = malloc(bufSize);
int nroom = 4; // sizeof(room) - 1;
for (int count = 0; count < 3; count++)
{
int ipick = rand() % nroom;
char *pick = room[ipick];
room[ipick] = room[--nroom];
snprintf(current, bufSize, "%s/file-%d.txt", dirname, count);
FILE *f = fopen(current, "w");
if (f != 0)
{
fprintf(f, "YOUR ROOM: %s\n", pick);
fclose(f);
}
}
return 0;
}
有很多小的更正。一个更大的代码是在使用单词时打乱单词列表的代码。另一个是为 nroom
设置的值.我将生活简化为常数 4;你可以使用 sizeof(room) / sizeof(room[0])
相反,它会随着数组的增长而增长。我使用了数组初始值设定项而不是赋值——并且可以省略 4
来自数组大小(它会根据初始化程序中的值的数量自动调整大小)。
每次运行都会产生相同的结果(相同内容的相同文件集)。添加#include <time.h>
到标题和 srand(time(0));
在循环之前在不同的运行中获得不同的结果。这是一种非常简单的随机数生成器播种方式。 getpid()
而不是 time(0)
也有一些优点。
我是一名优秀的程序员,十分优秀!