c - 指针关闭后,无法使用system()命令删除文件,并显示该文件已被其他程序使用
问题描述
之后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", ×);//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 块在:
//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 块。
除此之外,您最好使用remove()
删除文件。system()
将启动整个命令 shell 会话只是为了执行任务,因此是一个相当重量级的解决方案。
推荐阅读
- ionic-framework - mobilefirst js 以 ionic serve 开头(未定义 WL)
- reactjs - 到达和字体真棒
- javascript - 为什么 HTML DOM 事件不会立即影响同一个 DOM 元素?
- react-native - 添加风味后Android构建失败
- c++ - c++函数中Const用法的区别
- elasticsearch - elasticsearch.yml ses 电子邮件配置
- android - Android应用小部件背景形状以编程方式更改颜色不透明度
- zalenium - Windows - zalenium 文件上传
- http-live-streaming - 使用 EXT-X-BYTERANGE 动态生成 m3u8 列表
- ios - 在我的 iPhone 7,8 和 iOS 10,11 中从 Xcode 9.4 运行我的应用程序时,我在控制台中得到了一些这些打印