gpt4 book ai didi

c - 指针关闭后,无法使用system()命令删除该文件,并显示该文件已被其他程序使用

转载 作者:行者123 更新时间:2023-11-30 21:05:19 25 4
gpt4 key购买 nike

fclose(fpointer)之后,我尝试使用system("del text_file.txt");删除该文件,但输出显示“该进程无法访问该文件,因为该文件正在被另一个进程使用。”

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

FILE * fpointer;

int main() {
int times;
char option;

//Read the file
if ((fpointer = fopen("file_open.txt", "r")) == NULL) //If this file dont exist
{
fpointer = fopen("file_open.txt", "w");//Create the file
fprintf(fpointer, "0");
fclose(fpointer);
fpointer = fopen("file_open.txt", "r");//Reopen with reading mode
}
else
{
fpointer = fopen("file_open.txt", "r");
}
fscanf(fpointer, "%d", &times);//Save the number of note to variable
fclose(fpointer);

//Add 1 times when the program launch
fpointer = fopen("file_open.txt", "w");
times++;
fprintf(fpointer, "%d", times);//Save current variable to file
fclose(fpointer);

printf("You have launch this program %d times!\n", times);
printf("Do you want to reset the number?(Y/N)\n>>");
scanf(" %c", &option);

if (option == 'Y')
{
system("del file_open.txt");//delete the file
}
else
{
printf("\nThe program is exiting now...\n");
_getch();//Press any key to exit
exit(0);
}

return 0;
}

注意:

1)假设输入始终正确。

2) 我试图不将 file_open.txt 替换为 1

是否可以使用system("del text_file.txt")删除文件?

编辑:修复了一些错误。

编辑:

我尝试在我的代码中使用remove(),这是我修改的部分:

if (option == 'Y')
{
int status;
char file_name[] = "file_open.txt";
status = remove(file_name);//delete the file
if (status == 0)
{
printf("%s file deleted successfully.\n", file_name);
}
else
{
printf("Unable to delete the file\n");
perror("Following error occurred");
}
}
else
{
printf("\nThe program is exiting now...\n");
_getch();//Press any key to exit
exit(0);
}

通过删除fopen(fpointer)解决了问题,谢谢。

最佳答案

else block :

//Read the file
if ((fpointer = fopen("file_open.txt", "r")) == NULL) //If this file dont exist
{
...
}
else
{
fpointer = fopen("file_open.txt", "r");
}

将第二次打开该文件(或者在某些情况下可能无法打开它),但它将替换fpointer,因此您无法再关闭第一次打开的文件。因此,您打开了该文件两次,但只关闭了一次,并且通过覆盖它丢失了关闭第一个文件所需的句柄。 else block 应该被删除。

除此之外,您最好使用remove()来删除文件。 system() 将启动整个命令 shell session 来执行任务,因此是一个相当重量级的解决方案。

关于c - 指针关闭后,无法使用system()命令删除该文件,并显示该文件已被其他程序使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55207476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com