临时文件的创建以及自动创建临时文件名和添加临时文件扩展名

临时文件的创建:

 1 #define  _CRT_SECURE_NO_WARNINGS
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 
 5 // tmpfile产生临时文件,关闭文件或者程序关闭,就会自动删除
 6 // 创建临时文件
 7 void main()
 8 {
 9     FILE *ptemp;
10     ptemp = tmpfile();// 创建临时文件 返回文件指针
11     if (ptemp==NULL)
12     {
13         printf("临时文件创建失败!");
14         return;
15     }
16     fputs("学C真是好,好到不得了",ptemp);// 输出文本
17     rewind(ptemp);// 将文件指针移动到开头 可以进行读取
18     char str[512];
19     fgets(str, 512, ptemp);// 获取字符串
20     puts(str);// 屏幕输出
21     fclose(ptemp);
22     system("pause");
23 }

 

自己产生临时文件名并添加临时文件扩展名:

 1 #define  _CRT_SECURE_NO_WARNINGS
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<string.h>
 5 // 产生临时文件名自己创建
 6 void main()
 7 {
 8     FILE *ptemp;// 创建一个文件指针
 9     char path[100];// 路径,保存临时文件名
10     tmpnam(path);// 生成一个临时文件名保存到path
11 
12     char *p = path;
13     while (*p!='\0')
14     {
15         if (*p=='.')// 替换字符的作用
16         {
17             *p = 'x';
18         }
19         p++;// 指针向前移动
20     }
21     strcat(path,".txt");// 为产生的临时文件添加扩展名  strcat连接的作用
22 
23     ptemp = fopen(path, "w+");// 按照可读可写打开路径
24     printf("路径是:%s\n",path);// 产生的临时文件在程序所在磁盘的根目录 
25     if (ptemp == NULL)
26     {
27         printf("文件打开失败!");
28     }
29 
30     fputs("你好世界!",ptemp);// 写入文本
31     fputs("你好中国!",ptemp);
32     rewind(ptemp);// 将文件指针移到开头
33     char str[512];
34     fgets(str,512,ptemp);
35     printf("%s",str);// 从文件读取字符串 输出
36     fclose(ptemp);
37 
38     system("pause");
39 }

 

posted on 2015-05-25 16:33  Dragon-wuxl  阅读(1145)  评论(2)    收藏  举报

导航