为了扩展标题,我正在使用结构创建一组房间,该函数本质上需要随机生成最多7个房间(共10个),而每次都生成起始和结束房间。然后,我尝试为每个房间结构生成一个文件并显示其PID,然后打开每个目录以写入或创建该文件。
因此,我正在生成这样的结构:
struct room
{
int id;
char* name;
int numOutboundConnections;
struct room* outboundConnections[6];
};
和
int main(int argc, char* argv[])
{
struct room Room1;
Room1.id = 0;
Room1.name = calloc(16, sizeof(char));
strcpy(Room1.name, "Forest");
然后,这是我尝试生成目录并在主目录中创建它们的尝试:
// Generate the "rooms" directory name
sprintf(dirname, "./browninz.room.%d", getpid());
// Generate the room names concatenated with the directory name
sprintf(dir0, "%s/Room1", dirname);
sprintf(dir1, "%s/Room2", dirname);
sprintf(dir2, "%s/Room3", dirname);
sprintf(dir3, "%s/Room4", dirname);
sprintf(dir4, "%s/Room5", dirname);
sprintf(dir5, "%s/Room6", dirname);
sprintf(dir6, "%s/Room7", dirname);
mkdir(dirname, 0777);
// Now opening the room files/directories to create or write them in the folder.
FILE *Room1 = fopen(dir0, "w+");
FILE *Room2 = fopen(dir1, "w+");
FILE *Room3 = fopen(dir2, "w+");
FILE *Room4 = fopen(dir3, "w+");
FILE *Room5 = fopen(dir4, "w+");
FILE *Room6 = fopen(dir5, "w+");
FILE *Room7 = fopen(dir6, "w+");
然后,这会导致我所有房间结构的错误:
In function ‘main’:
browninz.buildrooms.c:102:11: error: conflicting types for ‘Room1’
FILE *Room1 = fopen(dir0, "w+");
^
我将不胜感激,因为我对使用C语言进行编程还比较陌生,我似乎无法弄清楚。
最佳答案
您已经将Room1
声明为struct room
,不能将其重新声明为FILE *
。
我仍然不确定您要完成的目标,但是也许将FILE *
添加到房间结构中可能是您要的目标:
struct room
{
int id;
char* name;
int numOutboundConnections;
struct room* outboundConnections[6];
FILE *file;
};
...
Room1.file = fopen( dir0, "w+" );
当然,您需要在完成操作后记住
fclose( Room1.file )
。
关于c - 创建房间的结构,然后将每个房间写入各自的唯一文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60066502/