Knowledge point 15: advanced applications of files

1. File creation

1. The creat function: int creat(const char *path, int amode)
This function is in the header file <io.h>. If the function fails to execute, it returns -1 (but the return value alone cannot detect the cause of the error).
Among them, the parameter path is a string of the name of the created file, and the parameter amode is used to specify the access mode and to indicate whether the file is a binary file or a text file. In general, the value of amode is 0 when generating a standard archive file.

#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. Deletion of files

1. Remove function: The int remove(const char *filename)
function of remove is to delete files. If the execution is successful, the return value is 0; if it fails, it returns -1. Where filename is the file to be deleted.
Note: Before executing the remove function, you must first make sure that the file exists, and then close the pointer of the file, otherwise the deletion will cause an error.

#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. Rename the file

1. int rename(const char *oldname, const char *newname)
Rename function: If the rename is successful, it returns 0; otherwise, the return value is non-zero.
Note: Before executing rename, make sure that the file exists, the new file name cannot be repeated with the existing file, and the pointer to the file needs to be closed, otherwise the function execution will fail.

#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;
}

You can change the storage path of the file by changing the file name, which is equivalent to transferring the file .

Guess you like

Origin blog.csdn.net/Shao_yihao/article/details/113730793