首页 > 解决方案 > 指针关闭后,无法使用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", &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),谢谢。

标签: cfilepointers

解决方案


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 会话只是为了执行任务,因此是一个相当重量级的解决方案。


推荐阅读