I kinda have similar questions like this guy (coava) posted.
(Append Random Text without Repetition for File (C))
I've tried the solution given but it doesn't work for me, maybe because in my case I'm storing those file in the directory as well.
So my code pretty much looks like this:
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);
}
Then I get a seg.fault, I tried to modify
snprintf(currentFile,bufSize,"file-%d.txt",count);
into
snprintf(currentFile,bufSize,"file-%d.txt",dirname,count);
It didn't give seg.fault, but it just print outside the directory with the addition of inside of each file sometimes I got random value like
"connection host: @blablabla" or some junk symbol.
Is there something wrong in my for loop? Or is it somewhere else?
Aucun commentaire:
Enregistrer un commentaire