Home > 书山有路 > A test on mkstemp

A test on mkstemp

September 2nd, 2011 Leave a comment Go to comments
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * testmkstemp.c
 *
 *  Created on: Aug 31, 2011
 *      Author: zhuhuang
 */
 
//int mkstemp(char *template);
 
#include <apueerr.h>
int main(void)
{
	int filedes;
	char *temp1 = "/home/zhuhuang/try1XXXXXX";
	char temp2[] = "/home/zhuhuang/try2XXXXXX";
 
	if((filedes = mkstemp(temp2)) == -1) //Succeed.
		err_sys("mkstemp error");
	printf("temp2: %sn", temp2);
 
	if((filedes = mkstemp(temp1)) == -1) //Fail!!!!!
		err_sys("mkstemp error");
	printf("temp1: %sn", temp1);
 
	exit(0);
}

The output is shown below:

temp2: /home/zhuhuang/try2anKX9s

Pay attention to the second call of mkstemp on temp1. It failed. Check the definition of temp1 and temp2, we will know the reason. For temp1, it is a pointer to a string literal “/home/zhuhuang/try1XXXXXX”, which is placed somewhere in the memory. The string literal is a constant. We can not use pointers that point to it to change its contents. That’s why mkstemp failed, since it tried to modify the contents pointed by temp1 to the name it has generated. For temp2, it is an array of characters. The string literal “/home/zhuhuang/try2XXXXXX” is used to initialized array temp2. But the contents of the array can be changed. So first call of mkstemp on temp2 succeeded.

Here is a page that will be useful for understanding character pointers: http://c-faq.com/~scs/cclass/krnotes/sx8e.html

Categories: 书山有路 Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.