我正在尝试打开文件并使用C附加到它们。我根据进程ID动态命名目录,并根据循环中随机选择的“房间”创建文件名。我的目的是打开文件,将房间名称附加到文件中,然后关闭文件并移动到下一个房间并执行相同的功能。我遇到的问题是“开放”。它似乎只返回-1,表示错误。错误消息表明“权限被拒绝”。我对此感到困惑,因为我似乎在open函数中设置了适当的权限。我尝试使用fopen(),但是一直产生分段错误11.我的roomFilePath声明和用法是否存在问题,或者我的使用是不正确的?以下是包含该问题的代码部分。 makeRooms()函数是我检查文件是否正确打开的地方。谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#define NUM_ROOMS 10
#define NUM_USED_ROOMS 7
#define MAX_CONNECTIONS 6
time_t t;
char* usedRooms[NUM_USED_ROOMS];
int i;
char directoryName[100];
char* baseDirectory = "walterer.rooms.";
int processId;
char roomFilePath[75];
int adjacencyMatrix[7][7] = {0};
int useableConnections;
int e;
int totConnections = 0;
int openRoom;
int file_descriptor;
char* roomNames[] = {
"cleveland",
"columbus",
"dallas",
"toledo",
"miami",
"sarasota",
"boston",
"chicago",
"denver",
"phoenix"
};
int connections[10] = {
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
};
void makeDirectory() {
processId = getpid();
sprintf(directoryName, "%s%d", baseDirectory,processId);
//printf("%s\n", directoryName);
mkdir(directoryName, 777);
}
void makeRooms() {
/* Initializes random number generator */
srand((unsigned) time(&t));
/* Create 7 rooms */
for(i = 0; i < NUM_USED_ROOMS; ){
/* Generate random number between 0 to 10 */
int randomNumber = rand() % NUM_ROOMS;
/* Loop as long the array does not contain any connections at the index */
while(connections[randomNumber] == 0) {
/* Append the room path to the end of my ONID path */
sprintf(roomFilePath,"%s/%s", directoryName, roomNames[randomNumber]);
printf("%s\n",roomFilePath);
/* Create file */
FILE *filePointer;
/* Open file to append*/
//filePointer = open(roomFilePath, O_WRONLY | O_CREAT, 0600);
//!!!Returning -1
file_descriptor = open(roomFilePath, O_APPEND, 0600);
printf("%d\n",file_descriptor);
if (file_descriptor == -1)
{
printf("open() failed on \"%s\"\n", roomFilePath);
perror("In createRooms()");
exit(1);
}
/*if (filePointer == NULL)
{
fprintf(stderr, "Error Creating File\n");
printf("something went wrong with read()! %s\n", strerror(errno));
}*/
/* Print the room name in the file */
/* SEG FAULT HERE!!!! */
fprintf(filePointer, "ROOM NAME: %s\n", roomNames[randomNumber]);
/* Close the file */
//fclose(filePointer);
usedRooms[i] = roomNames[randomNumber];
connections[randomNumber] = 1;
//printf("Room %d is %s \n", i+1, roomNames[randomNumber]);
i++;
}
}
}