1,文件的创建
1,creat函数:int creat(const char *path, int amode)
该函数在头文件<io.h>中。如果函数执行失败,返回 -1(但仅凭返回值,不能检测出错的原因)。
其中,参数path是所创建文件名称的字符串,参数amode用来指定访问的模式和标明该文件为二进制文件还是文本文件。一般情况下,生成一个标准存档文件时amode的值为0。
#include <stdio.h>
#include <io.h>
int main()
{
int h;
char filename[20];
printf("请输入要创建的文件名:");
scanf("%s", filename);
h = creat(filename, 0);
if (h == -1)
printf("文件已存在或路径错误!\n");
else
printf("文件创建成功!\n");
return 0;
}
2,文件的删除
1,remove函数:int remove(const char *filename)
remove函数的作用是删除文件。如果执行成功,返回值为0;如果失败,返回 -1。其中filename是要删除的文件。
注意:在执行remove函数前,首先要确定文件存在,之后要关闭该文件的指针,否则删除将出错。
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("F:\\shao.txt", "r");
fclose(fp);//关闭指向该文件的指针
int h;
h = remove("F:\\shao.txt") ;
if (h == 0)
printf("delete successfully");
else
printf("fail to delete");
return 0;
}
3,文件的重命名
1,rename函数:int rename(const char *oldname, const char *newname)
若重命名成功则返回0;否则返回值非0。
注意:执行rename之前,要保证文件存在,且新文件名不能与已有的文件重复,且关于该文件的指针需要关闭,否则函数执行失败。
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("F:\\shao.txt", "r");
fclose(fp);
int h;
h = rename("F:\\shao.txt", "F:\\test.txt");
if (h == 0)
printf("change successfully");
else
printf("fail to change");
return 0;
}
可以通过更改文件名的方式,改变文件的存储路径,此时相当于转移文件。