【发布时间】:2017-05-04 10:18:12
【问题描述】:
我有一个函数 printtree 可以打印出一棵树。 我在互联网上搜索了很多地方,发现 mmap 是分配内存和写入文件的好方法。
我想使用 mmap 将 printtree 的内容打印到文件中。我是第一次学习 mmap,我不知道该怎么做。
printtree()如下:
void printtree(struct Node *root, int indent)
{
int i;
if(root != NULL)
{
printtree(root->right,indent + 1);
for(i = 0;i<indent;i++)
{
printf("\t");
}
printf("%d\n",root->key);
printtree(root->left,indent + 1);
}
}
在我的 main.c 中,我正在尝试这个:
struct Node *root = NULL;
int info ;
int *arr;
int choice;
int fd;
int mode = 0x0777;
struct stat mystat;
void *p;
int size;
FILE *file_ptr;
if (argc != 2){ printf("Error\nIncorrect number of arguments\n");exit(1);}
if (access(argv[1],F_OK) != -1)
{
fd = open(argv[1],O_RDWR);
if (fd == -1)
{
perror("open");
exit(1);
}
if(fstat(fd, &mystat)<0)
{
perror("fstat");
close(fd);
exit(1);
}
p = mmap(0,mystat.st_size , PROT_READ | PROT_WRITE,
MAP_SHARED ,fd,0);
if(p == MAP_FAILED)
{
perror("mmap");
close(fd);
exit(1);
}
while(1)
{
printf("1.Insert\n");
printf("2.Delete\n");
printf("3.Lookup\n");
printf("4.Print\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value to be inserted : ");
scanf("%d", &info);
//write(fd,&info,36);
if( (root = insert(root,info)) == 0){}
else
break;
case 2:
printf("Enter the value you want to delete : ");
scanf("%d",&info);
root = deleteNode(root,info);
break;
case 4:
printtree(root,0);
break;
//printf("%s",arr[0]);
printf("\n");
break;
case 5:
close(fd);
exit(1);
case 3:
printf("Enter the element you want to look for : ");
scanf("%d",&info);
Search(root,info);
break;
case 6:
printtree(root,0);
break;
default:
printf("Wrong choice\n");
}
}
}
【问题讨论】:
-
Sooo... 有什么问题?如何重现它?
-
如何将printtree函数写入文件?有什么我需要用 mmap 来写的吗?
-
不清楚你在问什么。您是要存储树还是将其内容打印到文件中?
-
将其内容打印到文件中
-
将树存储到文件中是什么意思?